In C ++, which is better than i> -1 or i> = 0

This may be a dumb question, but such optimization sometimes improves the performance of your application. Here I ask specifically for C ++, because the way to compile C ++ code is very different from that of C # or Java.

The question is which one works best if the variable i is int.

  • i > -1
  • i >= 0

I am looking for performance in terms of the required memory block or registers and processor cycles required for both conditions.

Thanks in advance.

+6
source share
3 answers

In assembly language, both are in the same structure:

  • i > -1

     cmp [register with i value],-1 jg [somewhere] 
  • i >= 0

     cmp [register with i value],0 jge [somewhere] 

According to the transition flags used , the jg command does two flag mappings (ZF = 0 and SF = OF), but jge does only one (SF = OF).

So, I am tempted to say that both use almost the same registers and processor cycles, possibly a very quick comparison for i >= 0 .

+14
source

Well, logically,> an operation may be "cheaper" than> =, but I think you are compiling with the optimization option turned on, so maybe the compiler does everything it wants to optimize your code, so I would say, even if someone it's really faster, maybe the compiler will change it to a better option

+2
source

When writing a for loop, it can be useful to convert it from for (i = 0; i < 1000; i++) to for (i = 1000; i > 0; i--) , because on some architectures the compiler may skip the comparison statement, since the flag will be set when I reach 0. On modern architectures, I'm not sure if this is important.

0
source

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


All Articles