Skip to content

Commit 90b66c3

Browse files
committed
perf(utils): single-buffer ID() + shortRand — 5 allocs → 1
ID() built its 30-char output by chaining four allocating helpers: Concat → FormatUint → RandomBytes → HexEncode, each allocating an intermediate string that was discarded by the next stage. Rewrite: build into a single 32-byte slice via strconv.AppendUint + hex.AppendEncode, hand to AsString for the zero-copy return. Same crypto-random entropy source (cryptorand.Read into a 3-byte stack buffer) so the security shape is unchanged. shortRand() same pattern — one alloc instead of two. Bench impact (Apple M3 Ultra): Utils_ID 128.8 ns / 64 B / 5 allocs → 72.89 ns / 32 B / 1 alloc 1.8x faster, 80% alloc reduction
1 parent 7d1874e commit 90b66c3

1 file changed

Lines changed: 31 additions & 4 deletions

File tree

utils.go

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@
55

66
package core
77

8+
import (
9+
cryptorand "crypto/rand"
10+
"encoding/hex"
11+
"strconv"
12+
)
13+
814
// --- ID Generation ---
915

1016
var idCounter AtomicUint64
@@ -14,16 +20,37 @@ var idCounter AtomicUint64
1420
//
1521
// id := core.ID() // "id-1-a3f2b1"
1622
// id2 := core.ID() // "id-2-c7e4d9"
23+
//
24+
// Implementation: builds into a single pre-sized []byte then handed to
25+
// AsString — one heap allocation total even when the prefix + counter
26+
// + hex suffix would otherwise each cost a string. Previously cost 5
27+
// allocs through Concat / FormatUint / RandomBytes / HexEncode / final.
1728
func ID() string {
18-
return Concat("id-", FormatUint(idCounter.Add(1), 10), "-", shortRand())
29+
// "id-" + uint64 (max 20 digits) + "-" + 6 hex chars = 30 cap.
30+
buf := make([]byte, 0, 32)
31+
buf = append(buf, "id-"...)
32+
buf = strconv.AppendUint(buf, idCounter.Add(1), 10)
33+
buf = append(buf, '-')
34+
35+
var rnd [3]byte
36+
if _, err := cryptorand.Read(rnd[:]); err != nil {
37+
buf = append(buf, "000000"...)
38+
} else {
39+
buf = hex.AppendEncode(buf, rnd[:])
40+
}
41+
return AsString(buf)
1942
}
2043

44+
// shortRand returns 6 hex characters of crypto-random data, or "000000"
45+
// on entropy failure. Used by Fs.WriteAtomic to suffix temp filenames.
2146
func shortRand() string {
22-
r := RandomBytes(3)
23-
if !r.OK {
47+
buf := make([]byte, 0, 6)
48+
var rnd [3]byte
49+
if _, err := cryptorand.Read(rnd[:]); err != nil {
2450
return "000000"
2551
}
26-
return HexEncode(r.Value.([]byte))
52+
buf = hex.AppendEncode(buf, rnd[:])
53+
return AsString(buf)
2754
}
2855

2956
// --- Validation ---

0 commit comments

Comments
 (0)