Skip to content

Instantly share code, notes, and snippets.

@bastengao
Created November 10, 2021 03:05
Show Gist options
  • Save bastengao/397a3f3e8c0d30217b32d87afebb36ff to your computer and use it in GitHub Desktop.
Save bastengao/397a3f3e8c0d30217b32d87afebb36ff to your computer and use it in GitHub Desktop.
Go slice performance benchmark
package main
import "testing"
func BenchmarkInitLen(b *testing.B) {
n := b.N
for i := 0; i < n; i++ {
a := make([]int64, n)
for j := 0; j < n; j++ {
a[j] = int64(j)
}
}
}
func BenchmarkInitCap(b *testing.B) {
n := b.N
for i := 0; i < n; i++ {
a := make([]int64, 0, n)
for j := 0; j < n; j++ {
a = append(a, int64(j))
}
}
}
func BenchmarkZero(b *testing.B) {
n := b.N
for i := 0; i < n; i++ {
var a []int64
for j := 0; j < n; j++ {
a = append(a, int64(j))
}
}
}
func BenchmarkInitZeroLen(b *testing.B) {
n := b.N
for i := 0; i < n; i++ {
a := make([]int64, 0)
for j := 0; j < n; j++ {
a = append(a, int64(j))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment