开发者

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?


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


Assuming you talk about applying these to base types and no own classes where they could make a huge difference they can produce the same output especially when optimization is turned on. To my surprise I often found in decompiled applications that x += 1 is used over x++ on assembler level(add vs inc).


Any decent compiler should be able to recognize that the two are the same so in the end there should be no performance difference between them.

If you want to convince yourself just do a benchmark..


When you say "it could add up in the long run" - don't think about it that way.

Rather, think in terms of percentages. When you find the program counter is in that exact code 10% or more of the time, then worry about it. The reason is, if the percent is small, then the most you could conceivably save by improving it is also small.

If the percent of time is less than 10%, you almost certainly have much bigger opportunities for speedup in other parts of the code, almost always in the form of function calls you could avoid.

Here's an example.


Consider you're a lazy compiler implementer and wouldn't bother writing OPTIMIZATION routines in the machine-code-gen module.

x = x + 1;

would get translated to THIS code:

mov $[x],$ACC
iadd $1,$ACC
mov $ACC,$[x]

And x++ would get translated to:

incr $[x] ;increment by 1

if ONE instruction is executed in 1 machine cycle, then x = x + 1 would take 3 machine cycles where as x++ would take 1 machine cycle. (Hypothetical machine used here).

BUT luckily, most compiler implementers are NOT lazy and will write optimizations in the machine-code-gen module. So x = x+1 and x++ SHOULD take equal time to execute. :-P

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜