递增:x++ vs x += 1 [英] Incrementing: x++ vs x += 1

查看:63
本文介绍了递增:x++ vs x += 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到许多开发人员为了清晰起见使用 x += 1 而不是 x++.我知道 x++ 对新开发者来说可能是模棱两可的,而且 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?

使用for循环的例子:

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.

另一个例子:

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

对比

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

可以将 x++ 替换为 x += 1 而不会有任何性能损失吗? 我特别关心第二个示例,因为我使用的是两行而不是一行.

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.

如何增加数组中的一项?someArray[i]++ 在大循环中执行时会比执行 someArray[i] += 1 更快吗?

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.

这篇关于递增:x++ vs x += 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆