If i have a line like
if 1 == 2 {
fmt.Println(“1 = 2 for some reason”)
}
Since this will never be true, Does it still take compute time? Same with if statements that CAN be true but aren’t.
Will it take more compute time for a true if statement than a false? (Not including content of the if statement)
package bench
import (
"fmt"
)
func bench1() {
if 1 == 2 {
fmt.Println("1 = 2 for some reason")
}
}
func bench2() {
if 1 == 1 {
// fmt.Println("1 = 1 for some reason")
}
}
bench_test.go
package bench
import (
"testing"
)
func BenchmarkBench1(b *testing.B) {
for n := 0; n < b.N; n++ {
bench1()
}
}
func BenchmarkBench2(b *testing.B) {
for n := 0; n < b.N; n++ {
bench2()
}
}
$ go test -bench=.
goos: darwin
goarch: amd64
BenchmarkBench1-4 2000000000 0.41 ns/op
BenchmarkBench2-4 2000000000 0.40 ns/op
PASS
ok golangbridge/7/bench 1.674s
In that same article, see “A note on compiler optimizations”. I would be surprised if both your benchmarks weren’t reduced to an identical zero instructions by the optimizer.
Which also answers the original question - do not worry about the cost of a constant branch. Probably the compiler will optimize it out. If it doesn’t, the CPU branch prediction will be 100% accurate and never see the branch.