Standard library tour
These are the packages you use every day. Each one has one idiom to know and one trap that costs a production bug. The outputs and costs below come from real runs.
- 1Check the package before you write a loop. Most small helpers arrived between Go 1.21 and 1.27.
- 2A scanner, a buffered writer and a decoder report errors late. Check Err, Flush and Close.
- 3A time.Time from time.Now holds two clocks. Compare with Equal, and format in UTC.
- 4A path from a client goes through os.Root. String checks on the path miss symlinks.
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
long := strings.Repeat("x", 70_000)1
input := "first\n" + long + "\nthird\n"
sc := bufio.NewScanner(strings.NewReader(input))
lines := 0
for sc.Scan()2 {
lines++
}
fmt.Println("lines:", lines)3
}- 1Longer than the scanner limit of 64 KB.
- 2Returns false at the long line, as it does at the end of the input.
- 3The program prints a count and exits 0. Nothing shows that it stopped early.
| program | recorded output | status |
|---|---|---|
| As shown | lines: 1 | 2 lines lost |
| Print sc.Err() | lines: 1 err: bufio.Scanner: token too long | You see the failure |
| sc.Buffer with 1 MB, print sc.Err() | lines: 3 err: <nil> | All lines |
- The input has 3 lines. The first program counts 1.
- A loop on Scan ends on end of input and on any error. Only Err tells the two apart.
- The same pattern applies to rows.Next in database/sql and to a Decoder loop.
- Line-based logs and CSV exports reach 64 KB in production, and rarely in a test.
A Scanner stops at a line over 64 KB and returns false. I set a larger Buffer and I always check Err.
| the job | what people hand-write | use this | since |
|---|---|---|---|
| Find an element | A for loop with a flag | slices.Contains, slices.IndexFunc | 1.21 |
| Remove duplicates | A map of seen values | slices.Sort, then slices.Compact | 1.21 |
| Sorted map keys | Append to a slice, then sort it | slices.Sorted(maps.Keys(m)) | 1.23 |
| Sort by several fields | Nested if statements | cmp.Or(cmp.Compare(...), ...) | 1.22 |
| First value that is set | if x == "" { x = def } | cmp.Or(x, def) | 1.22 |
| Copy a map, clear a map | A loop over the keys | maps.Clone, clear(m) | 1.21 |
| Split at the first separator | strings.Index and two slices | strings.Cut | 1.18 |
| Split at the last separator | strings.LastIndex and two slices | strings.CutLast | 1.27 |
| Remove a known prefix | HasPrefix, then s[n:] | strings.CutPrefix | 1.20 |
| Loop over lines or fields | strings.Split, which allocates a slice | strings.Lines, strings.FieldsSeq | 1.24 |
| A date layout | "2006-01-02" typed by hand | time.DateOnly, time.DateTime | 1.20 |
| A path that stays in a folder | HasPrefix(path, base) | os.Root | 1.24 |
| Structured logs with levels | A wrapper around log.Printf | log/slog | 1.21 |
| Match an error type | var e *T, then errors.As(err, &e) | errors.AsType[*T](err) | 1.26 |
| A UUID | A third-party module | uuid.New, uuid.NewV7 | 1.27 |
| Lazy setup, one time | A mutex and a bool | sync.OnceValue (see G11) | 1.21 |
| Start and wait for goroutines | Add, go, defer Done | wg.Go (see G11) | 1.25 |
Before I write a helper, I check slices, maps, strings and cmp. In a 45-minute build, each helper I skip saves a test too.
| rule | status |
|---|---|
| Assign the result: s = slices.Delete(s, i, j) | Approved |
| Sort before Compact or BinarySearch | Approved |
| slices.Clone before you change a slice you received | Approved |
| Keep a second slice of the array after Delete, Compact or Insert | It sees zeros or moved data |
| Use maps.Keys as a slice | It is an iterator |
| Depend on the order of a map range | The order is random |
| Use slices.SortFunc when equal rows must keep their order | Use SortStableFunc |
| Use == on slices or maps | Use slices.Equal, maps.Equal |
cmp.Compare and slices.Sort order NaN before every other float. The < operator does not.
Delete and Compact change the array in place. I use the slice they return, and I forget every other slice of that array.
// SortPeople orders by team, then oldest first, then name.
func SortPeople(people []Person) {
slices.SortFunc1(people, func(a, b Person) int {
return cmp.Or(2
cmp.Compare(a.Team, b.Team),
cmp.Compare(b.Age, a.Age)3,
cmp.Compare(a.Name, b.Name),
)
})
}- 1The function returns negative, zero or positive. It is not stable.
- 2A plain function: Go evaluates every comparison before the call. A costly key belongs in an if statement.
- 3b before a: oldest first.
// TopWords returns the n most used words, most used first.
func TopWords(text string, n int) []WordCount {
counts := map[string]int{}
for w := range strings.FieldsSeq1(strings.ToLower(text)) {
counts[w]++
}
out := make([]WordCount, 0, len(counts))
for _, w := range slices.Sorted(maps.Keys(counts))2 {
out = append(out, WordCount{w, counts[w]})
}
slices.SortStableFunc3(out, func(a, b WordCount) int {
return cmp.Compare(b.Count, a.Count)
})
return out[:min(n, len(out))]
}- 1Iterates without a result slice.
- 2Sorted keys remove the random map order.
- 3Stable: words with equal counts keep the sorted order, so the output is the same on each run.
cmp.Or returns the first comparison that is not zero, so each sort key is one line. To reverse a key, I swap the arguments.
| call | time | allocs | status |
|---|---|---|---|
| sort.Slice(s, less) | 76.2 µs | 3 | Existing code |
| sort.Sort(byAge(s)) | 50.4 µs | 1 | Needs 3 methods |
| slices.SortFunc(s, f) | 66.5 µs | 0 | Approved |
- sort.Slice takes any, then swaps elements through reflection.
- slices.SortFunc is generic, so the compiler checks the element type.
- sort.Sort passes indexes. SortFunc copies two rows per comparison, so its gain depends on the row size.
- For a large struct, sort pointers or use indexes. Measure before you change it.
New code uses slices.SortFunc. It is typed, and it has no allocations. The sort package remains for existing code.
| rule | why | status |
|---|---|---|
| Builder or Join for many parts | 959 ns against 9.4 µs for 100 parts. | Approved |
| strconv over fmt for one number | 19.3 ns against 63.5 ns. | Approved |
| Pass a bit size to ParseInt and ParseUint | It rejects a value that does not fit. | Approved |
| Use errors.Is with ErrRange, ErrSyntax | The error wraps them. | Approved |
| TrimLeft to remove a prefix | It takes a set of characters. | Use TrimPrefix |
| len(s) to count characters | It counts bytes. Use utf8.RuneCountInString. | Not approved |
| Keep buf.Bytes() past the next write | It aliases the buffer. | Use bytes.Clone |
| Split("", ",") as an empty list | It returns one empty string. | Check len(s) |
Strings are immutable, so += in a loop copies everything. I use a Builder or Join, and strconv for numbers on a hot path.
// ParseHeader splits "Key: value" at the first colon.
func ParseHeader(line string) (key, value string, err error) {
key, value, ok := strings.Cut(line, ":")1
if !ok {
return "", "", fmt.Errorf("%w4: %q", ErrBadHeader, line)
}
return strings.TrimSpace(key), strings.TrimSpace(value), nil
}
// SplitExt splits "a.tar.gz" at the last dot, into "a.tar" and "gz".
func SplitExt(name string) (base, ext string) {
base, ext, ok := strings.CutLast(name, ".")2
if !ok {
return name, ""
}
return base, ext
}
// ParsePort reads a TCP port. The bit size rejects 70000.
func ParsePort(s string) (uint16, error) {
n, err := strconv.ParseUint(s, 10, 16)3
if err != nil {
return 0, fmt.Errorf("port %q: %w", s, err)
}
return uint16(n), nil
}- 1Splits at the first colon, so a colon in the value stays there.
- 2Go 1.27.
- 3Base 10, 16 bits. It rejects 70000 and -1.
- 4Wraps the error, so errors.Is finds strconv.ErrRange.
Cut replaces Index and two slices, and it returns found as a bool, so the not-found case is one branch.
- The wall clock tells the time. The monotonic clock measures it.
- A comparison uses the monotonic reading only when both values have one.
- On some systems the monotonic clock stops while the machine sleeps.
time.Now holds a wall reading and a monotonic reading. Time.Since uses the monotonic one, so an NTP step cannot make it negative.
| rule | why | status |
|---|---|---|
| time.Since(start) for elapsed time | It uses the monotonic reading. | Approved |
| Multiply by the unit: 5 * time.Second | A bare 5 is 5 ns. | Approved |
| Equal to compare two times | == also compares the zone pointer and the monotonic reading. | Approved |
| Time as a map key | The key holds the same three fields. | Use UnixNano or Round(0).UTC() |
| AddDate(0, 1, 0) for "next month" | January 31 becomes March 3 in 2026. | Clamp the day yourself |
| Add(24 * time.Hour) for "tomorrow" | A day with a clock change has 23 or 25 hours. | Use AddDate for dates |
| A literal Z in a layout | It prints Z in any zone, with local digits. | Use RFC3339 |
The reference date is Mon Jan 2 15:04:05 MST 2006: month 1, day 2, hour 3 (15), minute 4, second 5, year 6, zone offset -7.
A Duration is an int64 of nanoseconds. Layouts use the reference date, and I store and send UTC.
t.Format
2026-03-07T14:35:03+05:30
Parses back without the 0.25 s.
the moment
2026-03-07T09:05:03.25Z
- Pick a layout and a zone. The result shows the text that Format wrote.
- The second line is what a reader gets from that text alone. The reader has no other information about the zone.
- RFC3339 drops the fraction, and RFC3339Nano keeps it. In this list, only those two keep the zone offset.
I send RFC3339 in UTC. A layout with no zone, or with a literal Z, gives a reader the wrong moment.
// Valid reports whether the token has time left.
func (t Token) Valid() bool {
return time.Now().Before(t.Expires)1
}
// Issue makes a token that lives for ttl.
func Issue(value string, ttl time.Duration) Token {
return Token{Value: value, Expires: time.Now().Add(ttl)}
}
// Timed returns how long f took, on the monotonic clock.
func Timed(f func()) time.Duration {
start := time.Now()
f()
return time.Since(start)2
}
// Stamp formats a moment for an API: UTC, fixed layout.
func Stamp(t time.Time) string {
return t.UTC().Format(time.RFC3339)3
}- 1Plain time.Now. The code has no clock parameter.
- 2Monotonic, also for a run that crosses a clock change.
- 3One zone and one layout for every API response.
func TestTokenExpires(t *testing.T) {
synctest.Test1(t, func(t *testing.T) {
tok := Issue("abc", time.Hour)
time.Sleep(time.Hour - time.Nanosecond)2
if !tok.Valid() {
t.Fatal("expired too early")
}
time.Sleep(time.Nanosecond)3
if tok.Valid() {
t.Fatal("still valid at the expiry")
}
})
}- 1The bubble clock starts at midnight UTC on 2000-01-01.
- 2Every goroutine in the bubble is blocked, so the clock jumps at once.
- 3The test checks the exact boundary. A real clock cannot do this.
I do not inject a clock interface for this. In a synctest bubble, time.Now and time.Sleep use a fake clock, so the test takes no real time.
| rule | status |
|---|---|
| io.Copy to stream, with a LimitReader on input you do not trust | Approved |
| bufio.Writer for many small writes: 160 ns against 3.2 µs per line | Approved |
| Return the error from Flush, and from Close on a file you wrote | Approved |
| Check Scanner.Err after every Scan loop | Approved |
| Read returns n > 0 and an error together. Use the n bytes first | Approved |
| io.ReadAll on a body or file with no limit | Memory follows the input |
| defer f.Close() on a written file, error ignored | A failed write is lost |
| Exit with data in a bufio.Writer | The bytes are lost |
// CountLines counts lines of up to limit bytes each.
func CountLines(r io.Reader, limit int) (int, error) {
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 64*1024), limit)1
lines := 0
for sc.Scan() {
lines++
}
if err := sc.Err()2; err != nil {
return lines, fmt.Errorf("line %d: %w", lines+1, err)
}
return lines, nil
}- 1Start at 64 KB. The buffer grows up to limit.
- 2The fix from panel A.
// Save copies r to w, stops at limit bytes, and returns the
// SHA-256 of what it wrote.
func Save(w io.Writer, r io.Reader, limit int64) (string, error) {
h := sha256.New()
src := io.LimitReader(r, limit+1)1
n, err := io.Copy(io.MultiWriter(w, h)2, src)
if err != nil {
return "", fmt.Errorf("copy: %w", err)
}
if n > limit {
return "", fmt.Errorf("input over %d bytes", limit)
}
return hex.EncodeToString(h.Sum(nil)), nil
}- 1One byte more than the limit, so the code can tell at the limit from over it.
- 2Every byte goes to the file and to the hash, with no second read.
I compose readers and writers instead of loading a file. Copy streams, LimitReader bounds it, and MultiWriter hashes it on the way.
| rule | why | status |
|---|---|---|
| filepath for OS paths, path for URLs | filepath uses the OS separator. path always uses a slash. | Approved |
| WalkDir, not Walk | Walk calls Lstat on every file. | Approved |
| errors.Is(err, fs.ErrNotExist) | It sees through the wrapped path error. | Approved |
| Temp file in the target folder, then Rename | Rename replaces the file in one step on one filesystem. | Approved |
| Join(base, clientPath) as a safety check | ../.. leaves base after the clean. | Not approved |
| HasPrefix(path, base) | A symlink inside base leaves it. | Not approved |
| os.WriteFile for a file that readers open | A reader can see a partial file. | Use a rename |
filepath.Join cleans the path, so it does not protect anything. A client path needs IsLocal or, better, os.Root.
// WriteLines replaces path in one step. A reader sees the old
// file or the new file, never a partial one.
func WriteLines(path string, lines []string) (err error) {
dir := filepath.Dir(path)
f, err := os.CreateTemp(dir, ".tmp-*")1
if err != nil {
return fmt.Errorf("create temp: %w", err)
}
defer func() {
if err != nil {
err = errors.Join(err, os.Remove(f.Name())2)
}
}()
w := bufio.NewWriter(f)
for _, l := range lines {
if _, err := fmt.Fprintln(w, l); err != nil {
return errors.Join(fmt.Errorf("write: %w", err), f.Close()5)
}
}
if err := w.Flush()3; err != nil {
return errors.Join(fmt.Errorf("flush: %w", err), f.Close())
}
if err := f.Sync()4; err != nil {
return errors.Join(fmt.Errorf("sync: %w", err), f.Close())
}
if err := f.Close(); err != nil {
return fmt.Errorf("close: %w", err)
}
if err := os.Rename(f.Name(), path); err != nil {
return fmt.Errorf("rename: %w", err)
}
return nil
}- 1The same folder, so Rename stays on one filesystem.
- 2On any failure the temp file goes, and the old file stays.
- 3Without it the last 4 KB stays in memory.
- 4Puts the bytes on disk before the rename makes them visible.
- 5Close can report a failed write, so its error counts here.
I write to a temp file in the same folder, sync it, then rename it. A reader sees the old file or the new one.
// ReadUpload reads a file by a name the client chose. The
// root refuses a path or a symlink that leaves dir.
func ReadUpload(dir, name string) ([]byte, error) {
root, err := os.OpenRoot(dir)1
if err != nil {
return nil, fmt.Errorf("open root: %w", err)
}
defer root.Close()
b, err := root.ReadFile(name)2
if err != nil {
return nil, fmt.Errorf("read upload: %w", err)
}
return b, nil
}- 1Holds the folder open. Later paths resolve against it, step by step.
- 2The kernel call runs relative to the open folder, so a rename race cannot redirect it.
| name from the client | os.ReadFile | root.ReadFile |
|---|---|---|
| ok | Read "hi" | Read "hi" |
| ../secret | Read "key" | Refused |
| link | Read "key" | Refused |
- The row "link" is a symlink inside the folder that points outside it. A string check on the name passes it.
- An open root costs about the same as os.ReadFile: 23.6 µs against 24.4 µs.
- Opening the root for each call costs 42.6 µs. A server keeps one root open.
- Root.FS gives an fs.FS for http.FileServerFS or templates.
os.Root is opened on a folder, and each path resolves from there. A dot-dot path or a symlink that leaves the folder fails.
// Secret logs as a fixed text, whatever it holds.
type Secret string
// LogValue is called by every handler.
func (Secret) LogValue() slog.Value1 {
return slog.StringValue("[redacted]")
}
type requestIDKey struct{}
// WithRequestID stores the ID that every log line will carry.
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestIDKey{}, id)
}
// contextHandler copies the request ID from ctx to the record.
type contextHandler struct{ slog.Handler }2
func (h contextHandler) Handle(
ctx context.Context, r slog.Record,
) error {
if id, ok := ctx.Value(requestIDKey{}).(string); ok {
r.AddAttrs(slog.String("request_id", id))3
}
return h.Handler.Handle(ctx, r)
}
// NewLogger writes JSON lines at the level in lvl, which a
// running program can change.
func NewLogger(w io.Writer, lvl *slog.LevelVar4) *slog.Logger {
opts := &slog.HandlerOptions{Level: lvl}
return slog.New(contextHandler{slog.NewJSONHandler(w, opts)})
}- 1Every handler calls LogValue, so one type rule covers all call sites.
- 2Embedding keeps Enabled, WithAttrs and WithGroup. Only Handle changes.
- 3Reads the ID from the ctx of InfoContext. Plain Info passes a background context.
- 4Set changes the level while the program runs, with no restart.
| rule | status |
|---|---|
| Use InfoContext, and pass the request ctx | Approved |
| Use log.With for fields of one request or job | Approved |
| Let the level gate the cost: 11.9 ns off, 754 ns on | Approved |
| Use slog.DiscardHandler in tests that do not read logs | Approved |
| Build a costly value before a Debug call | Use LogValuer |
| Key and value lists with a missing value | !BADKEY, see the drill |
| Log a struct that holds a password | Use LogValuer |
| Log inside a tight loop at Info | Use a metric |
A disabled line costs a level check and the arguments. In this benchmark neither case allocates.
Every line carries a request ID from the context. A secret type logs as redacted, whichever call site logs it.
| since | what changed | what it means here |
|---|---|---|
| 1.20 | strings and bytes CutPrefix, CutSuffix. time.DateTime, DateOnly, TimeOnly, Time.Compare. filepath.IsLocal. errors.Join. | Named layouts replace typed ones. |
| 1.21 | Packages slices, maps, cmp and log/slog. Built-in min, max and clear. | Most small helpers are no longer needed. |
| 1.22 | cmp.Or. slices.Concat. Delete, DeleteFunc, Compact, CompactFunc and Replace zero the freed tail. Insert always panics on a bad index. | A second slice of the array sees zeros. |
| 1.23 | Iterators: slices.Sorted, Collect, Chunk, All, Values; maps.Keys, Values, All. slices.Repeat. os.CopyFS. filepath.Localize. | maps.Keys returns an iterator, not a slice. |
| 1.24 | os.Root. strings and bytes Lines, SplitSeq, FieldsSeq. slog.DiscardHandler. testing.B.Loop. | Paths from clients have a safe API. |
| 1.25 | Root adds ReadFile, WriteFile, MkdirAll, Rename, RemoveAll and more. testing/synctest. slog.GroupAttrs and Record.Source. | Root now covers the usual file calls. |
| 1.26 | io.ReadAll uses less memory. bytes.Buffer.Peek. slog.NewMultiHandler. errors.AsType. | One logger can write to two handlers. |
| 1.27 | strings.CutLast and bytes.CutLast. New package uuid. go test runs the stdversion vet check. encoding/json/v2 (see G15). | UUIDs need no third-party module. |
| when | the moment | what to do or say |
|---|---|---|
| build | The prompt asks for a list in a fixed order. | slices.SortFunc with cmp.Or. Add the ID as the last key, so the order is total and the test is stable. |
| build | A store is a map, and a test compares results. | slices.Sorted(maps.Keys(m)). Map order changes between runs and fails a test only sometimes. |
| build | A rule depends on the current time. | Call time.Now, and test inside synctest.Test. The test is exact and instant. |
| build | The service must read a file of records. | bufio.Scanner with Buffer and Err, or a json.Decoder (see G15). |
| talk | "How do you store timestamps?" | UTC in the database, RFC3339 on the wire, local zone only at display time. |
| talk | "How do you log in production?" | slog with a JSON handler, a request ID from the context, and a LevelVar I can change at run time. |
| talk | "A client names a file. What can go wrong?" | Path traversal, by dot-dot or by symlink. os.Root refuses both. |
| talk | "Why not sort.Slice?" | It works. SortFunc has a typed function and no allocations. For code that runs, I keep it until a change touches it. |
I use the standard library first. I add a dependency only when I can name what the standard library cannot do.
0 of 12 known
Predict the output.
package main import ( "fmt" "time" ) func main() { t := time.Date(2026, 3, 7, 9, 5, 0, 0, time.UTC) fmt.Println(t.Format("YYYY-MM-DD")) fmt.Println(t.Format("2006-01-02")) swapped := "2006-02-01" fmt.Println(t.Format(swapped)) }Predict the output.
package main import ( "fmt" "time" ) func main() { a := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) india := time.FixedZone("IST", 5*3600+1800) b := a.In(india) fmt.Println(a == b, a.Equal(b)) now := time.Now() wall := now.Round(0) fmt.Println(now == wall, now.Equal(wall)) }Predict the output.
package main import ( "fmt" "time" ) func main() { jan31 := time.Date(2026, 1, 31, 0, 0, 0, 0, time.UTC) fmt.Println(jan31.AddDate(0, 1, 0).Format(time.DateOnly)) }Predict the output.
package main import ( "fmt" "time" ) func main() { seconds := 30 fmt.Println(time.Duration(seconds)) fmt.Println(time.Duration(seconds) * time.Second) d := 90 * time.Minute fmt.Println(d, d.Hours(), int(d.Hours())) }Predict the output.
package main import ( "fmt" "strings" ) func main() { fmt.Printf("%q\n", strings.Split("", ",")) fmt.Printf("%q\n", strings.Split("a,,b", ",")) fmt.Printf("%q\n", strings.Fields("")) fmt.Printf("%q\n", strings.Fields(" a b ")) }Predict the output.
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.TrimLeft("abacus", "ab")) fmt.Println(strings.TrimPrefix("abacus", "ab")) fmt.Println(strings.TrimSuffix("report.go.go", ".go")) fmt.Println(strings.TrimRight("report.go.go", ".go")) }Predict the output.
package main import ( "errors" "fmt" "strconv" ) func main() { n, err := strconv.ParseInt("300", 10, 8) fmt.Println(n, err) fmt.Println(errors.Is(err, strconv.ErrRange)) fmt.Println(string(rune(65)), strconv.Itoa(65)) }Predict the output.
package main import ( "fmt" "slices" ) func main() { a := []int{1, 2, 1, 2, 2} fmt.Println(slices.Compact(a)) b := []int{1, 2, 1, 2, 2} slices.Sort(b) fmt.Println(slices.Compact(b)) }Predict the output.
package main import ( "fmt" "slices" ) func main() { a := []int{1, 2, 3, 4} b := slices.Delete(a, 1, 2) fmt.Println(a, len(a)) fmt.Println(b, len(b)) }Predict the output.
package main import ( "bytes" "fmt" ) func main() { var buf bytes.Buffer buf.WriteString("first") saved := buf.Bytes() copied := bytes.Clone(saved) buf.Reset() buf.WriteString("SECOND") fmt.Println(string(saved), string(copied)) }Predict the output. The program has two print calls.
package main import ( "bufio" "fmt" "os" ) func main() { w := bufio.NewWriter(os.Stdout) fmt.Fprintln(w, "written to the buffer") fmt.Println("buffered bytes:", w.Buffered()) }Predict the output. The time attribute is removed for a stable result.
package main import ( "log/slog" "os" ) func main() { h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey { return slog.Attr{} } return a }, }) log := slog.New(h) args := []any{"user", 7, "orphan"} log.Info("saved", args...) log.Debug("hidden") }
- sort 1,000
- 66.5 µs with 0 allocations; sort.Slice 76.2 µs with 3.
- concat 100
- 762 ns Join; 959 ns Builder; 9.4 µs with +=.
- one int
- 11.6 ns AppendInt; 19.3 ns Itoa; 63.5 ns Sprintf.
- time.Now
- 65.7 ns, with no allocation.
- slog line
- 754 ns as JSON; 11.9 ns below the level.
- file write
- 3.2 µs per line; 160 ns with bufio.
- ratio
- bufio makes small writes about 20 times cheaper.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.