java for 效率_Java for循环中i++和++i在效率等方面有什么区别?

++i will increment the value of i, and then return the incremented value.

i = 1; j = ++i; (i is 2, j is 2)

i++ will increment the value of i, but return the original value that i held before being incremented.

i = 1; j = i++; (i is 2, j is 1)

For a for loop, either works. ++i seems more common, perhaps because that is what is used in

In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.

The efficiency question is interesting... here's my attempt at an answer:

(First, it is far from obvious that ++i is more efficient than i++, at least where integer variables are concerned.

And :So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish. I submit that if you are not using the value of the expression, there is never a reason to use i++ instead of ++i, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away.

So, if the resulting value is not used, I would use ++i. But not because it is more efficient: because it correctly states my intent.)

As operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.https://stackoverflow.com/questions/24853/c-what-is-the-difference-between-i-and-i​stackoverflow.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值