I have a while loop inside which I want to do a specific operation only once, and a different operation for all other loop runs.
while (..) {
if ( 0 == count ) {
// do_this
} else {
// do_that
}
count++;
}
Here, count
needs to be compared with 0
only once but it is unnecessarily compared in each loop run. Is there an alternative way where the comparison happens only once and once succeeded is not again called?
Either do the thing for count == 0
before the loop, or if that's not possible (because it's in the middle of other things that are being done) just write your code to be human readable and any half decent compiler will figure it out for you. Or it will not figure it out and the branch predictor in the CPU will do the job. Either way a nano-optimization like this will most likely cost you more time reading the code than you'll ever save on execution time.
{
// do_this
}
count = 1; /*assuming count previously started at zero*/
while (..) {
// do_that
count++; /*although some folk prefer ++count as it's never slower than count++*/
}
is better
Don't optimize unnecessarily!
The cost of the compare is 1-2 clock cycles and as mentioned by Art it could be optimized away by the compiler. The cost is absolutely negligable when compared to the cost of reading from a file. The performance of your program will be bound by I/O anyway (either memory reads or disk reads depending on whether the file is mapped in memory).
In this case you should write the code so that it is easy to maintain.
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