Skip to content

Instantly share code, notes, and snippets.

@syntaqx
Created June 24, 2015 22:46
Show Gist options
  • Save syntaqx/bd98b1b15d45da1b7778 to your computer and use it in GitHub Desktop.
Save syntaqx/bd98b1b15d45da1b7778 to your computer and use it in GitHub Desktop.
If/Else vs Switch
package main
import "strconv"
func Switch(n int) string {
code := strconv.Itoa(n)
switch {
case n >= 500:
code = ">=500"
case n >= 400:
code = ">=400"
case n >= 300:
code = ">=300"
}
return code
}
func If(n int) string {
code := strconv.Itoa(n)
if n >= 500 {
code = ">=500"
} else if n >= 400 {
code = ">=400"
} else if n >= 300 {
code = ">=300"
}
return code
}
package main
import "testing"
func BenchmarkSwitch(b *testing.B) {
for n := 0; n < b.N; n++ {
Switch(200)
Switch(300)
Switch(400)
Switch(500)
}
}
func BenchmarkIf(b *testing.B) {
for n := 0; n < b.N; n++ {
If(200)
If(300)
If(400)
If(500)
}
}
BenchmarkSwitch 10000000 226 ns/op
BenchmarkIf 10000000 224 ns/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment