Created
September 11, 2013 17:14
-
-
Save kisielk/6526766 to your computer and use it in GitHub Desktop.
A benchmark of slice versus map iteration. Go 1.1.
This file contains 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 iterate | |
import "testing" | |
func BenchmarkSlice100(b *testing.B) { benchmarkSlice(b, 100) } | |
func BenchmarkSlice1000(b *testing.B) { benchmarkSlice(b, 1000) } | |
func BenchmarkSlice10000(b *testing.B) { benchmarkSlice(b, 10000) } | |
func BenchmarkSlice100000(b *testing.B) { benchmarkSlice(b, 100000) } | |
func benchmarkSlice(b *testing.B, n int) { | |
s := make([]int, n) | |
for i := 0; i < n; i++ { | |
s[i] = i | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for _, _ = range s { | |
} | |
} | |
} | |
func BenchmarkMap100(b *testing.B) { benchmarkMap(b, 100) } | |
func BenchmarkMap1000(b *testing.B) { benchmarkMap(b, 1000) } | |
func BenchmarkMap10000(b *testing.B) { benchmarkMap(b, 10000) } | |
func BenchmarkMap100000(b *testing.B) { benchmarkMap(b, 100000) } | |
func benchmarkMap(b *testing.B, n int) { | |
m := make(map[int]int, n) | |
for i := 0; i < n; i++ { | |
m[n] = n | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for _, _ = range m { | |
} | |
} | |
} |
This file contains 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
BenchmarkSlice100 20000000 121 ns/op | |
BenchmarkSlice1000 1000000 1170 ns/op | |
BenchmarkSlice10000 200000 11658 ns/op | |
BenchmarkSlice100000 10000 116510 ns/op | |
BenchmarkMap100 5000000 670 ns/op | |
BenchmarkMap1000 200000 9249 ns/op | |
BenchmarkMap10000 20000 76125 ns/op | |
BenchmarkMap100000 2000 798339 ns/op |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment