Skip to content

Instantly share code, notes, and snippets.

@mateothegreat
Created April 17, 2023 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mateothegreat/d9861a63a57491803c5cea93b05d93df to your computer and use it in GitHub Desktop.
Save mateothegreat/d9861a63a57491803c5cea93b05d93df to your computer and use it in GitHub Desktop.
Slices vs. Array performance in golang.
package main
import "testing"
var gs = make([]byte, 1000)
var ga [1000]byte
func BenchmarkSliceGlobal(b *testing.B) {
for i := 0; i < b.N; i++ {
for j, v := range gs {
gs[j]++
gs[j] = gs[j] + v + 10
gs[j] += v
}
}
}
func BenchmarkArrayGlobal(b *testing.B) {
for i := 0; i < b.N; i++ {
for j, v := range ga {
ga[j]++
ga[j] = ga[j] + v + 10
ga[j] += v
}
}
}
func BenchmarkSliceLocal(b *testing.B) {
var s = make([]byte, 1000)
for i := 0; i < b.N; i++ {
for j, v := range s {
s[j]++
s[j] = s[j] + v + 10
s[j] += v
}
}
}
func BenchmarkArrayLocal(b *testing.B) {
var a [1000]byte
for i := 0; i < b.N; i++ {
for j, v := range a {
a[j]++
a[j] = a[j] + v + 10
a[j] += v
}
}
}
@mateothegreat
Copy link
Author

go test -bench=. -benchmem
goos: darwin
goarch: arm64
pkg: scratch
BenchmarkSliceGlobal-10           758868              1574 ns/op               0 B/op          0 allocs/op
BenchmarkArrayGlobal-10          2258762               532.8 ns/op             0 B/op          0 allocs/op
BenchmarkSliceLocal-10           2263557               528.1 ns/op             0 B/op          0 allocs/op
BenchmarkArrayLocal-10           1946401               615.5 ns/op             0 B/op          0 allocs/op
PASS
ok      scratch 7.511s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment