diff options
author | Agniva De Sarker <agnivade@yahoo.co.in> | 2017-08-13 23:45:04 +0530 |
---|---|---|
committer | Ian Lance Taylor <iant@golang.org> | 2017-08-15 14:35:34 +0000 |
commit | 22cfe24aca80653b0e8efdd4a1aba1df00e8e72d (patch) | |
tree | 316975f90be4008b181c4bac8040a06906c34a88 /src/encoding/hex | |
parent | 2351bbfd3b11122936fc5858be826d1da413bab3 (diff) | |
download | go-22cfe24aca80653b0e8efdd4a1aba1df00e8e72d.tar.gz go-22cfe24aca80653b0e8efdd4a1aba1df00e8e72d.zip |
encoding/hex: save allocation in DecodeString()
The destination slice does not need to be created at all. The source
slice itself can be used as the destination because the decode loop
increments by one and then the 'seen' byte is not used anymore. Therefore
the decoded byte can be stored in that index of the source slice itself.
This trick cannot be applied to EncodeString() because in that case,
the destination slice is large than the source. And for a single byte
in the source slice, two bytes in the destination slice is written.
func BenchmarkDecodeString(b *testing.B) {
for i := 0; i < b.N; i++ {
DecodeString("0123456789abcdef")
}
}
name old time/op new time/op delta
DecodeString 71.0ns ± 6% 58.0ns ± 0% -18.28% (p=0.008 n=5+5)
name old alloc/op new alloc/op delta
DecodeString 16.0B ± 0% 8.0B ± 0% -50.00% (p=0.008 n=5+5)
name old allocs/op new allocs/op delta
DecodeString 1.00 ± 0% 1.00 ± 0% ~ (all equal)
Change-Id: Id98db4e712444557a804155457a4dd8d1b8b416d
Reviewed-on: https://go-review.googlesource.com/55611
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Diffstat (limited to 'src/encoding/hex')
-rw-r--r-- | src/encoding/hex/hex.go | 7 |
1 files changed, 4 insertions, 3 deletions
diff --git a/src/encoding/hex/hex.go b/src/encoding/hex/hex.go index 2768f1bac6..18e0c09ef3 100644 --- a/src/encoding/hex/hex.go +++ b/src/encoding/hex/hex.go @@ -94,12 +94,13 @@ func EncodeToString(src []byte) string { // DecodeString returns the bytes represented by the hexadecimal string s. func DecodeString(s string) ([]byte, error) { src := []byte(s) - dst := make([]byte, DecodedLen(len(src))) - _, err := Decode(dst, src) + // We can use the source slice itself as the destination + // because the decode loop increments by one and then the 'seen' byte is not used anymore. + len, err := Decode(src, src) if err != nil { return nil, err } - return dst, nil + return src[:len], nil } // Dump returns a string that contains a hex dump of the given data. The format |