I have done my best and read a lot of Q&As on SO.SE, but I haven't found an answer to my particular question. Most for-loop
and break
related question refer to nested loops, while I am concerned with performance.
I want to know if using a break
inside a for-loop
has an impact on the performance of my C++ code (assuming the break gets almost never called). And if it has, I would also like to know tentatively how big the penalization is.
I am quite suspicions that it does indeed impact performance (although I do not know how much). So I wanted to ask you. My reasoning goes as follows:
Independently of the extra code for the conditional statements that trigger the
break
(like anif
), it necessarily ads additional instructions to my loop.Further, it probably also messes around when my compiler tries to unfold the
for-loop
, as it no longer knows the number of iterations that will run at compile time, effectively rendering it into awhile-loop
.Therefore, I suspect it does have a performance impact, which could be considerable for very fast and tight loops.
So this takes me to a follow-up question. Is a for-loop
& break
performance-wise equal to a while-loop
? Like in the following snippet, where we assume that checkCondition()
evaluates 99.9% of the time as true
. Do I loose the performance advantage of the for-loop
?
// USING WHILE
int i = 100;
while( i-- && checkCondition())
{
// do stuff
}
// USING FOR
for(int i=100; i; --i)
{
if(checkCondition()) {
// do stuff
} else {
break;
}
}
I have tried it on my computer, but I get the same execution time. And being wary of the compiler and its optimization voodoo, I wanted to know the conceptual answer.
EDIT:
Note that I have measured the execution time of both versions in my complete code, without any real difference. Also, I do not trust compiling with -s
(which I usually do) for this matter, as I am not interested in the particular result of my compiler. I am rather interested in the concept itself (in an academic sense) as I am not sure if I got this completely right :)