![]() ![]() |
|
![]() ![]() |
I love when people talk about loop optimization and use |
![]() ![]() |
New compilers are intelligent enough to take care of that small ++i and i++ difference. And if we talk strictly about the syntax, both are correct. |
![]() ![]() |
Piyush Soni wrote:Hmmm... apparently you are right. Just ran some benchmarks. This must be a recent change in JavaScript. Probably the result using a JIT compiler instead of an interpreter. Piyush Soni wrote:Not really. Post-increment has to makes a copy(or at least its supposed to without optimizations turned on), which isn't needed when you have a single statement. Post-increment does something extra that's unnecessary and thus a pre-increment is syntactically the better choice. Just because both will work doesn't mean both are correct. In fact, if you are going to use a post-increment you should put it in the conditional of the for loop: for (var i = 0, len = arr.length; i++ < len;) {}
|
![]() ![]() |
sizzlemctwizzle wrote: Well, as I said, if we talk *strictly* about syntax, both are correct('Correct' - syntactically, and logically). In fact, if we consider C/C++, not only i++ or ++i but any valid arithmetic expression would be 'syntactically correct' at that place(or no expression at all, as you wrote in your example above), *not considering performance*. |
![]() ![]() |
Piyush Soni wrote:I don't wanna talk about syntax in the strict sense. I wanna talk about real world usage. In that case ++i is correct(or a least more correct) syntactically. Sure optimizers are probably smart enough to fix it for you, but why not just skip that step and use the correct syntax in your code? But this discussion has become kind of pointless, because I do agree with you that in the strict syntactic sense both are valid, and I think you agree that ++i is better at least from a performance standpoint. |
![]() ![]() |
Yes, I agree on that. Even if optimizations are turned on, it is always a good practice to use ++i in place of i++. |



