C / C ++ compare only once

I have a while loop inside which I want to perform a specific operation only once and another operation for all other loops.

while (..) { if ( 0 == count ) { // do_this } else { // do_that } count++; } 

Here count needs to be compared with 0 only once, but it is unnecessary to compare it in each run of the cycle. Is there an alternative way, when the comparison occurs only once and succeeds once, is not called again?

+6
source share
3 answers

Either do the thing for count == 0 before the loop, or if this is not possible (because it is in the middle of the other things that are being executed), just write your code so that it is readable, and any half-worthy compiler will understand it for you . Or it will not be clarified, and the branch predictor in the CPU will do the job. In any case, national optimizations like this will most likely cost you more time to read the code than ever before at runtime.

+18
source
 { // do_this } count = 1; /*assuming count previously started at zero*/ while (..) { // do_that count++; /*although some folk prefer ++count as it never slower than count++*/ } 

it is better

+8
source

Do not optimize unnecessarily!

The cost of comparison is 1-2 cycles, and, as mentioned in Art, it can be optimized by the compiler. The cost is absolutely negligible compared to the cost of reading from a file. The performance of your program will in any case be related to I / O (reading or reading disks depending on whether the file is displayed in memory).

In this case, you must write code to make it easy to maintain.

+3
source

Source: https://habr.com/ru/post/954386/


All Articles