Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ compare only once [duplicate]

Tags:

c++

c

loops

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?

like image 559
user13107 Avatar asked Sep 23 '13 07:09

user13107


3 Answers

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.

like image 189
Art Avatar answered Nov 20 '22 01:11

Art


{
    // 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

like image 39
Bathsheba Avatar answered Nov 20 '22 01:11

Bathsheba


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.

like image 21
Klas Lindbäck Avatar answered Nov 20 '22 02:11

Klas Lindbäck