Created
September 8, 2022 12:36
-
-
Save Deleplace/f35dbf06dc00afe03e8ea658212c7c2c to your computer and use it in GitHub Desktop.
Benchmark heavy use of append vs. heavy use of slices.Insert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package insert | |
import ( | |
"fmt" | |
"testing" | |
"golang.org/x/exp/slices" | |
) | |
func BenchmarkGrow(b *testing.B) { | |
for _, M := range []int{ | |
10, | |
1_000, | |
100_000, | |
} { | |
{ | |
name := fmt.Sprintf("append_%d", M) | |
b.Run(name, func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var a []int | |
for j := 0; j < M; j++ { | |
a = append(a, 0) | |
} | |
Sink = a | |
} | |
}) | |
} | |
{ | |
name := fmt.Sprintf("insert_%d", M) | |
b.Run(name, func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var a []int | |
for j := 0; j < M; j++ { | |
a = slices.Insert(a, 0, 0) | |
} | |
Sink = a | |
} | |
}) | |
} | |
} | |
} | |
// Prevent optimizing things away | |
var Sink []int |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
slices.Insert
needs to be O(N) because it is shifting up to N elements to the right. However, it could do much fewer allocations, by doubling (or 1.25x-ing) capacity when needed, likeappend
does.