Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing: x++ vs x += 1

I've read that many developers use x += 1 instead of x++ for clarity. I understand that x++ can be ambiguous for new developers and that x += 1 is always more clear, but is there any difference in efficiency between the two?

Example using for loop:

for(x = 0; x < 1000; x += 1) vs for(x = 0; x < 1000; x++)

I understand that it's usually not that big of a deal, but if I'm repeatedly calling a function that does this sort of loop, it could add up in the long run.

Another example:

while(x < 1000) {
    someArray[x];
    x += 1;
}

vs

while(x < 1000) {
    someArray[x++];
}

Can x++ be replaced with x += 1 without any performance loss? I'm especially concerned about the second example, because I'm using two lines instead of one.

What about incrementing an item in an array? Will someArray[i]++ be faster than doing someArray[i] += 1 when done in a large loop?

like image 829
beatgammit Avatar asked Jun 28 '11 16:06

beatgammit


People also ask

Which is better x ++ or x += 1?

Difference between x++ and x=x+1 in Java. In x++, it increase the value of x by 1 and in x=x+1 it also increase the value of x by 1. But the question is that both are same or there is any difference between them.

What is difference between x ++ and X 1?

x++ is a const expression that modifies the value of x (It increases it by 1 ). If you reference x++ , the expression will return the value of x before it is incremented. The expression ++x will return the value of x after it is incremented. x + 1 however, is an expression that represents the value of x + 1 .

Is X ++ the same as x += 1?

Hope this help with ++x and x++, not sure how to answer x+=1 though. Thank you for the explanation! x+=1 is the same as x=x+1 ++x; //prefix x++; //postfix Prefix increments the value, and then proceeds with the expression. Postfix evaluates the expression and then performs the incrementing.

Is ++ x and x ++ the same?

The only difference between the two is their return value. The former increments ( ++ ) first, then returns the value of x , thus ++x .


1 Answers

Any sane or insane compiler will produce identical machine code for both.

like image 199
SLaks Avatar answered Oct 27 '22 06:10

SLaks