Skip to content

Instantly share code, notes, and snippets.

@podanypepa
Created July 5, 2023 07:43
Show Gist options
  • Save podanypepa/c7d56d895f97eba36c86f63e1da145a8 to your computer and use it in GitHub Desktop.
Save podanypepa/c7d56d895f97eba36c86f63e1da145a8 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"testing"
)
func coreFunc(t int) error {
return nil
}
var (
errNotFound = errors.New("not found")
funcMap = map[int]func(int) error{
1: coreFunc,
2: coreFunc,
3: coreFunc,
4: coreFunc,
5: coreFunc,
}
)
func fMap(selector int) error {
return funcMap[selector](selector)
}
func fSwitch(selector int) error {
switch selector {
case 1:
return coreFunc(100)
case 2:
return coreFunc(100)
case 3:
return coreFunc(100)
case 4:
return coreFunc(100)
case 5:
return coreFunc(100)
}
return errNotFound
}
func BenchmarkMapFirst(b *testing.B) {
for i := 0; i < b.N; i++ {
fMap(1)
}
}
func BenchmarkMapLast(b *testing.B) {
for i := 0; i < b.N; i++ {
fMap(5)
}
}
func BenchmarkSwitchFirst(b *testing.B) {
for i := 0; i < b.N; i++ {
fSwitch(1)
}
}
func BenchmarkSwitchLast(b *testing.B) {
for i := 0; i < b.N; i++ {
fSwitch(5)
}
}
// Results
// goos: darwin
// goarch: arm64
// pkg: sw1
// BenchmarkMapFirst-10 309510448 3.683 ns/op
// BenchmarkMapLast-10 195455868 6.138 ns/op
// BenchmarkSwitchFirst-10 1000000000 0.4093 ns/op
// BenchmarkSwitchLast-10 1000000000 0.4091 ns/op
// PASS
// ok sw1 4.702s
@podanypepa
Copy link
Author

Remaping switch with cases to map implementation. Switch has const access time to any case path. Map is slower.

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