Switch better than if-else in Go?

Daryl Ng
1 min readFeb 17, 2021

I am sure you have wondered if switch is more efficient than if-else, or vice versa. So here is a little experiment to compare them.

  1. If-else
func If(i int) bool {
if i == 1 {
return true
} else {
return false
}
}

2. Switch with no condition

func Switch(i int) bool {
switch {
case i == 1:
return true
default:
return false
}
}

3. Switch with constants

func SwitchConst(i int) bool {
switch i {
case 1:
return true
default:
return false
}
}

And here are the benchmarks…

BenchmarkIf
BenchmarkIf-8 1000000000 0.268 ns/op 0 B/op 0 allocs/op
BenchmarkSwitch
BenchmarkSwitch-8 1000000000 0.267 ns/op 0 B/op 0 allocs/op
BenchmarkSwitchConst
BenchmarkSwitchConst-8 1000000000 0.263 ns/op 0 B/op 0 allocs/op

The above seems to show that switch is faster but that’s not the case (no pun intended).

Running the benchmark again yields a different outcome.

BenchmarkIf
BenchmarkIf-8 1000000000 0.270 ns/op 0 B/op 0 allocs/op
BenchmarkSwitch
BenchmarkSwitch-8 1000000000 0.265 ns/op 0 B/op 0 allocs/op
BenchmarkSwitchConst
BenchmarkSwitchConst-8 1000000000 0.276 ns/op 0 B/op 0 allocs/op

So there is no difference between switch and if-else. It is purely for aesthetic and code readability.

I prefer switch over if-else because it is easier to read but you might think otherwise. Don’t let others affect the way you code. Since there is no gain in performance, do it any way you like!

Do follow me if you have not already done so!

--

--