logoalt Hacker News

achandlerwhitetoday at 1:33 AM2 repliesview on HN

Isn’t there an implicit check to exit the loop?


Replies

Tiddles-the2ndtoday at 1:42 AM

The check isn't important; what's important is being predictable so the CPU can guess which way the check will go. I don't know exactly how it works, but after the first couple of loops, the predictor will assume it's always going to end up in the loop and make that the fast path. It may guess wrong the first couple of loops, and the last check wrong, but the other 997 will be correct.

show 1 reply
cstrahantoday at 1:44 AM

“that code” refers to the body of the loop.

Unless the loop is unrolled, yes, there is a branch to exit the loop. But then that doesn’t matter because the whole goal at the beginning was to avoid branch misprediction (which is not the same thing as avoiding branches entirely).