Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

arrays - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...