logoalt Hacker News

dekdroptoday at 2:14 AM4 repliesview on HN

If it's branch predicting, why would if statement run slow? How come unnecessary memory write is fine?


Replies

teo_zerotoday at 6:00 AM

In modern CPUs a mispredicted branch is much more expensive than a memory write.

The unsaid assumption is that the array is filled with random values between 0 and 1000, so the "if" condition has a 50% of chances to be true. The branch is mispredicted 50% of times.

Of course this trick won't work when the statement protected by "if" is a more complex and costly action, or one that can't be undone (in the example, note that when the counter is not incremented, the value written to memory will be overwritten in the next cycle, so it's "undone" in a certain way).

show 1 reply
gblarggtoday at 5:58 AM

Modern processors are pipelined, where they run a lot in advance of when the result is needed. A mispredicted branch requires throwing out all the advance calculations on the incorrectly followed path. The branch predictor can't predict branches like this based on data that tends to equally be distributed for taken and not taken. The memory write is fine because it's not conditional, so it can be pipelined along with everything else.

tancoptoday at 5:24 AM

[dead]