Skip to content

Instantly share code, notes, and snippets.

@Deleplace
Created July 26, 2023 16:19
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 Deleplace/b7dfa86783f6b3be524e0fccdad75eab to your computer and use it in GitHub Desktop.
Save Deleplace/b7dfa86783f6b3be524e0fccdad75eab to your computer and use it in GitHub Desktop.
Which of these 2 functions is fastest?
package bench
import "testing"
var fooMap = map[string]int{"a": 1, "b": 2}
func Foo1(s string) int {
return fooMap[s]
}
func Foo2(s string) int {
switch s {
case "a":
return 1
case "b":
return 2
default:
return 0
}
}
func BenchmarkFoo1(b *testing.B) {
for i := 0; i < b.N; i++ {
Sink += Foo1(A)
Sink += Foo1(B)
}
}
func BenchmarkFoo2(b *testing.B) {
for i := 0; i < b.N; i++ {
Sink += Foo2(A)
Sink += Foo2(B)
}
}
//
// Exported variables (won't be optimized away, or constant-propagated)
//
var Sink int
var A, B = "a", "b"
@Deleplace
Copy link
Author

% go test -bench=. -v
goos: darwin
goarch: arm64
BenchmarkFoo1
BenchmarkFoo1-10    	152906709	         7.861 ns/op
BenchmarkFoo2
BenchmarkFoo2-10    	508370997	         2.368 ns/op

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