Skip to content

encoding/hex: don't overallocate memory in DecodeString #67259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions src/encoding/hex/hex.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,9 @@ func EncodeToString(src []byte) string {
// If the input is malformed, DecodeString returns
// the bytes decoded before the error.
func DecodeString(s string) ([]byte, error) {
src := []byte(s)
// 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.
n, err := Decode(src, src)
return src[:n], err
dst := make([]byte, DecodedLen(len(s)))
n, err := Decode(dst, []byte(s))
return dst[:n], err
}

// Dump returns a string that contains a hex dump of the given data. The format
Expand Down
12 changes: 12 additions & 0 deletions src/encoding/hex/hex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,18 @@ func BenchmarkDecode(b *testing.B) {
}
}

func BenchmarkDecodeString(b *testing.B) {
for _, size := range []int{256, 1024, 4096, 16384} {
src := strings.Repeat("2b744faa", size/8)
b.Run(fmt.Sprintf("%v", size), func(b *testing.B) {
b.SetBytes(int64(size))
for i := 0; i < b.N; i++ {
sink, _ = DecodeString(src)
}
})
}
}

func BenchmarkDump(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)
Expand Down