Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Overview
This pull request optimizes the marshaling of tag sets. Previously the
strings.Join()
function was used with added a lot of memory allocations. The new implementation manually allocates and appends to a byte slice.The number of allocations has dropped to 3:
keys := make([]string, 0, len(tags))
sort.Strings(keys)
b := make([]byte, sz)
The new implementation manually handles the append instead of using the built-in
append()
function because appending astring
to a[]byte
requires a memory allocation whereas acopy()
does not.A table test suite was also added to verify correctness.
Benchmark
Previous implementation
$ go test -bench=BenchmarkMarshalTags -v PASS BenchmarkMarshalTags_KeyN1 2000000 824 ns/op 176 B/op 6 allocs/op BenchmarkMarshalTags_KeyN3 1000000 1319 ns/op 416 B/op 6 allocs/op BenchmarkMarshalTags_KeyN5 1000000 2173 ns/op 656 B/op 6 allocs/op BenchmarkMarshalTags_KeyN10 500000 3929 ns/op 1280 B/op 6 allocs/op
New implementation
$ go test -bench=BenchmarkMarshalTags -v PASS BenchmarkMarshalTags_KeyN1 3000000 458 ns/op 80 B/op 3 allocs/op BenchmarkMarshalTags_KeyN3 2000000 753 ns/op 160 B/op 3 allocs/op BenchmarkMarshalTags_KeyN5 1000000 1193 ns/op 240 B/op 3 allocs/op BenchmarkMarshalTags_KeyN10 500000 2477 ns/op 448 B/op 3 allocs/op