Skip to content

Commit a72fdb1

Browse files
committed
encoding/hex: don't over allocate memory in DecodeString
Change-Id: Ie9137639e2b39690f2246948d7ff58f09fc84e68
1 parent ad27916 commit a72fdb1

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/encoding/hex/hex.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,9 @@ func EncodeToString(src []byte) string {
136136
// If the input is malformed, DecodeString returns
137137
// the bytes decoded before the error.
138138
func DecodeString(s string) ([]byte, error) {
139-
src := []byte(s)
140-
// We can use the source slice itself as the destination
141-
// because the decode loop increments by one and then the 'seen' byte is not used anymore.
142-
n, err := Decode(src, src)
143-
return src[:n], err
139+
dst := make([]byte, DecodedLen(len(s)))
140+
n, err := Decode(dst, []byte(s))
141+
return dst[:n], err
144142
}
145143

146144
// Dump returns a string that contains a hex dump of the given data. The format

src/encoding/hex/hex_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,20 @@ func BenchmarkDecode(b *testing.B) {
275275
}
276276
}
277277

278+
func BenchmarkDecodeString(b *testing.B) {
279+
for _, size := range []int{256, 1024, 4096, 16384} {
280+
src := strings.Repeat("2b744faa", size/8)
281+
sink = make([]byte, size/2)
282+
283+
b.Run(fmt.Sprintf("%v", size), func(b *testing.B) {
284+
b.SetBytes(int64(size))
285+
for i := 0; i < b.N; i++ {
286+
sink, _ = DecodeString(src)
287+
}
288+
})
289+
}
290+
}
291+
278292
func BenchmarkDump(b *testing.B) {
279293
for _, size := range []int{256, 1024, 4096, 16384} {
280294
src := bytes.Repeat([]byte{2, 3, 5, 7, 9, 11, 13, 17}, size/8)

0 commit comments

Comments
 (0)