While playing with some simple code in Go I noticed that using a bool array instead of int array(which uses only values of 0/1) has a pretty significant speed-up.
- funcUsingBool - 1.397s
- funcUsingInt - 1.996s
I would have expected both of them to give the same performance since there isn't a native bool type at machine level, so I would have expected the compiler to generate similar assembly code.
Since the difference is pretty big, I'm skeptical on the validity of this result.
I'm building using the command "go build filename.go", but I'm not sure what's the equivalent flag of gcc's "-O3".
func funcUsingBool(n int) int {
if n < 1 { return 0 }
notPrime := make([]bool, n+1)
count := 1
for i := 3; i < n; i = i + 2 {
if notPrime[i] { continue }
count++
k := 2 * i
for k <= n {
notPrime[k] = true
k += i
}
}
return count
}
func funcUsingInt(n int) int {
if n < 1 { return 0}
notPrime := make([]int, n+1)
count := 1
for i := 3; i < n; i = i + 2 {
if notPrime[i] == 1 { continue }
count++
k := 2 * i
for k <= n {
notPrime[k] = 1
k += i
}
}
return count
}