Let say I have an array of 1,000,000 elements with about 90% of 0s and 10% of 1s.
In order to count of 1s, I can do
sum=0;
for(int i=0;i<size;i++) {
sum+=x[i]
}
But I thought maybe comparison is cheaper than addition so this would be better.
sum=0;
for(int i=0;i<size;i++) {
if(x[i]==1)
sum++;
}
But I am not sure. Which one is faster?
It is hard to say which one is going to be faster without trying it, but a even a slightly slower instruction without a branch will usually be faster due to pipelining and branch prediction.
In your case, the branch predictor will be wrong 90% of the time, reducing the speed quite a bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With