From 57370a87d80be0ab588eb8bb9a5e2a31f4613355 Mon Sep 17 00:00:00 2001 From: Alberto Donizetti Date: Wed, 17 Aug 2016 20:34:09 +0200 Subject: [PATCH] encoding/hex: change lookup table from string to array MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit 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 Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- src/encoding/hex/hex.go | 5 ++++- src/encoding/hex/hex_test.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/encoding/hex/hex.go b/src/encoding/hex/hex.go index 73a25034be..0211d23a18 100644 --- a/src/encoding/hex/hex.go +++ b/src/encoding/hex/hex.go @@ -12,7 +12,10 @@ import ( "io" ) -const hextable = "0123456789abcdef" +var hextable = [16]byte{ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'a', 'b', 'c', 'd', 'e', 'f', +} // EncodedLen returns the length of an encoding of n source bytes. func EncodedLen(n int) int { return n * 2 } diff --git a/src/encoding/hex/hex_test.go b/src/encoding/hex/hex_test.go index b969636cd5..64dabbd10a 100644 --- a/src/encoding/hex/hex_test.go +++ b/src/encoding/hex/hex_test.go @@ -6,6 +6,7 @@ package hex import ( "bytes" + "fmt" "testing" ) @@ -151,3 +152,18 @@ var expectedHexDump = []byte(`00000000 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 00000010 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d |./0123456789:;<=| 00000020 3e 3f 40 41 42 43 44 45 |>?@ABCDE| `) + +var sink []byte + +func BenchmarkEncode(b *testing.B) { + for _, size := range []int{256, 1024, 4096, 16384} { + src := bytes.Repeat([]byte{2, 3, 5, 7, 9, 11, 13, 17}, size/8) + sink = make([]byte, 2*size) + + b.Run(fmt.Sprintf("%v", size), func(b *testing.B) { + for i := 0; i < b.N; i++ { + Encode(sink, src) + } + }) + } +} -- 2.48.1