Created
July 26, 2023 16:19
-
-
Save Deleplace/b7dfa86783f6b3be524e0fccdad75eab to your computer and use it in GitHub Desktop.
Which of these 2 functions is fastest?
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 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" |
Author
Deleplace
commented
Jul 26, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment