Created
June 4, 2018 09:57
-
-
Save nolash/07907e493e06060251b71ea493f36522 to your computer and use it in GitHub Desktop.
benchmark map versus array retrievals in go
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 maparraybench | |
import ( | |
"fmt" | |
"os" | |
"testing" | |
) | |
const ( | |
itemCount = 100 | |
) | |
func init() { | |
fmt.Fprintf(os.Stderr, "benchmark with %d items\n", itemCount) | |
} | |
func BenchmarkMap(b *testing.B) { | |
m := make(map[string]int) | |
for i := 0; i < itemCount; i++ { | |
m[fmt.Sprintf("%x", i)] = i | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for k, v := range m { | |
_ = k | |
_ = v | |
} | |
} | |
} | |
func BenchmarkArray(b *testing.B) { | |
var a []int | |
for i := 0; i < itemCount; i++ { | |
a = append(a, i) | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for j, v := range a { | |
_ = v | |
_ = j | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment