Skip to content

Commit 0e8793a

Browse files
committed
Inline ndata() in concatkdf New
Write length-prefixed fields directly into a single buffer, eliminating intermediate allocations from ndata(). No measurable perf change (compiler already optimized via inlining + escape analysis): 54.6 ns/op, 128 B/op, 2 allocs.
1 parent 203ccf3 commit 0e8793a

File tree

2 files changed

+42
-14
lines changed

2 files changed

+42
-14
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package concatkdf_test
2+
3+
import (
4+
"crypto"
5+
"testing"
6+
7+
"github.com/lestrrat-go/jwx/v3/jwe/internal/concatkdf"
8+
)
9+
10+
func BenchmarkNew(b *testing.B) {
11+
hash := crypto.SHA256
12+
alg := []byte("A128CBC-HS256")
13+
z := make([]byte, 32)
14+
apu := []byte("Alice")
15+
apv := []byte("Bob")
16+
pubinfo := make([]byte, 4)
17+
privinfo := []byte{}
18+
19+
b.ReportAllocs()
20+
b.ResetTimer()
21+
for b.Loop() {
22+
kdf := concatkdf.New(hash, alg, z, apu, apv, pubinfo, privinfo)
23+
_ = kdf
24+
}
25+
}

jwe/internal/concatkdf/concatkdf.go

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,25 @@ type KDF struct {
1313
hash crypto.Hash
1414
}
1515

16-
func ndata(src []byte) []byte {
17-
buf := make([]byte, 4+len(src))
18-
binary.BigEndian.PutUint32(buf, uint32(len(src)))
19-
copy(buf[4:], src)
20-
return buf
21-
}
22-
2316
func New(hash crypto.Hash, alg, Z, apu, apv, pubinfo, privinfo []byte) *KDF {
24-
algbuf := ndata(alg)
25-
apubuf := ndata(apu)
26-
apvbuf := ndata(apv)
17+
// Write length-prefixed fields directly into a single buffer,
18+
// avoiding intermediate allocations from ndata().
19+
totalSize := (4 + len(alg)) + (4 + len(apu)) + (4 + len(apv)) + len(pubinfo) + len(privinfo)
20+
concat := make([]byte, totalSize)
21+
22+
n := 0
23+
binary.BigEndian.PutUint32(concat[n:], uint32(len(alg)))
24+
n += 4
25+
n += copy(concat[n:], alg)
26+
27+
binary.BigEndian.PutUint32(concat[n:], uint32(len(apu)))
28+
n += 4
29+
n += copy(concat[n:], apu)
30+
31+
binary.BigEndian.PutUint32(concat[n:], uint32(len(apv)))
32+
n += 4
33+
n += copy(concat[n:], apv)
2734

28-
concat := make([]byte, len(algbuf)+len(apubuf)+len(apvbuf)+len(pubinfo)+len(privinfo))
29-
n := copy(concat, algbuf)
30-
n += copy(concat[n:], apubuf)
31-
n += copy(concat[n:], apvbuf)
3235
n += copy(concat[n:], pubinfo)
3336
copy(concat[n:], privinfo)
3437

0 commit comments

Comments
 (0)