Skip to content

Commit e9db830

Browse files
authored
Reduce allocations in concatkdf Read (#1562)
* Reduce allocations in concatkdf Read Use h.Sum(k.buf) instead of append(k.buf, h.Sum(nil)...) to avoid intermediate slice allocation. Replace binary.Write with BigEndian.PutUint32 + h.Write to avoid its internal buffer alloc. Read: -7% time (225→208 ns/op), -10% mem (324→292 B/op), -1 alloc (6→5) * Fix benchmark lint: use b.Loop()
1 parent 168b5b9 commit e9db830

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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 BenchmarkRead(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+
out := make([]byte, 32)
24+
if _, err := kdf.Read(out); err != nil {
25+
b.Fatal(err)
26+
}
27+
}
28+
}

jwe/internal/concatkdf/concatkdf.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,13 @@ func New(hash crypto.Hash, alg, Z, apu, apv, pubinfo, privinfo []byte) *KDF {
4242
func (k *KDF) Read(out []byte) (int, error) {
4343
var round uint32 = 1
4444
h := k.hash.New()
45+
var roundBuf [4]byte
4546

4647
for len(out) > len(k.buf) {
4748
h.Reset()
4849

49-
if err := binary.Write(h, binary.BigEndian, round); err != nil {
50+
binary.BigEndian.PutUint32(roundBuf[:], round)
51+
if _, err := h.Write(roundBuf[:]); err != nil {
5052
return 0, fmt.Errorf(`failed to write round using kdf: %w`, err)
5153
}
5254
if _, err := h.Write(k.z); err != nil {
@@ -56,7 +58,7 @@ func (k *KDF) Read(out []byte) (int, error) {
5658
return 0, fmt.Errorf(`failed to write other info using kdf: %w`, err)
5759
}
5860

59-
k.buf = append(k.buf, h.Sum(nil)...)
61+
k.buf = h.Sum(k.buf)
6062
round++
6163
}
6264

0 commit comments

Comments
 (0)