Created
June 24, 2015 22:46
-
-
Save syntaqx/bd98b1b15d45da1b7778 to your computer and use it in GitHub Desktop.
If/Else vs Switch
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 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 | |
} |
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 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) | |
} | |
} |
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
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