Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addition vs comparison [closed]

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?

like image 638
Tae-Sung Shin Avatar asked Mar 10 '26 02:03

Tae-Sung Shin


1 Answers

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.

like image 145
Sergey Kalinichenko Avatar answered Mar 12 '26 14:03

Sergey Kalinichenko