Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, which is better i>-1 or i>=0 [duplicate]

This might be a silly question to ask, but this kind of optimization is sometimes boost performance of your application. Here I am asking specifically for C++, because the way C++ compile code is a lot different that c# or Java.

The question is which one performs better, if variable i is int.

  1. i > -1
  2. i >= 0

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

Thanks in advance.

like image 521
Yogesh Avatar asked May 22 '15 10:05

Yogesh


2 Answers

In assembly language, both are on the same structure:

  1. i > -1

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

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

According to used jump flags, the instruction jg make two flags comparaisons (ZF = 0 and SF = OF) but jge does only one (SF = OF).

So I'm tempted to say that both use almost same registers and CPU cycles, with maybe a very little quicker comparaison for i >= 0.

like image 82
Aracthor Avatar answered Oct 21 '22 06:10

Aracthor


Well, according to logic > operation may be "cheaper" than >=, but I guess you are compiling with Optimization option enabled, so probably the compiler do whatever he wants to optimize your code, so I would say that doesn't matter, even if one is really faster, probably the compiler change it to the best option

like image 36
angrykoala Avatar answered Oct 21 '22 08:10

angrykoala