Skip to content

Commit 57370a8

Browse files
ALTreebradfitz
authored andcommitted
encoding/hex: change lookup table from string to array
name old time/op new time/op delta Encode/256-4 431ns ± 2% 391ns ± 2% -9.36% (p=0.000 n=8+8) Encode/1024-4 1.68µs ± 0% 1.51µs ± 0% -9.91% (p=0.001 n=7+7) Encode/4096-4 6.68µs ± 0% 6.03µs ± 1% -9.69% (p=0.000 n=8+8) Encode/16384-4 27.0µs ± 1% 24.0µs ± 0% -11.03% (p=0.000 n=8+7) Change-Id: I6994e02f77797349c4e188377d84f97dffe98399 Reviewed-on: https://go-review.googlesource.com/27254 Reviewed-by: Brad Fitzpatrick <[email protected]> Run-TryBot: Brad Fitzpatrick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent 17eee31 commit 57370a8

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/encoding/hex/hex.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ import (
1212
"io"
1313
)
1414

15-
const hextable = "0123456789abcdef"
15+
var hextable = [16]byte{
16+
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
17+
'a', 'b', 'c', 'd', 'e', 'f',
18+
}
1619

1720
// EncodedLen returns the length of an encoding of n source bytes.
1821
func EncodedLen(n int) int { return n * 2 }

src/encoding/hex/hex_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package hex
66

77
import (
88
"bytes"
9+
"fmt"
910
"testing"
1011
)
1112

@@ -151,3 +152,18 @@ var expectedHexDump = []byte(`00000000 1e 1f 20 21 22 23 24 25 26 27 28 29 2a
151152
00000010 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d |./0123456789:;<=|
152153
00000020 3e 3f 40 41 42 43 44 45 |>?@ABCDE|
153154
`)
155+
156+
var sink []byte
157+
158+
func BenchmarkEncode(b *testing.B) {
159+
for _, size := range []int{256, 1024, 4096, 16384} {
160+
src := bytes.Repeat([]byte{2, 3, 5, 7, 9, 11, 13, 17}, size/8)
161+
sink = make([]byte, 2*size)
162+
163+
b.Run(fmt.Sprintf("%v", size), func(b *testing.B) {
164+
for i := 0; i < b.N; i++ {
165+
Encode(sink, src)
166+
}
167+
})
168+
}
169+
}

0 commit comments

Comments
 (0)