Forward or Backward loop?

in The Banana Bar
Subscribe to Forward or Backward loop? 7 posts, 3 voices



Avindra V.G. Scriptwright
FirefoxWindows

http://stackoverflow.com/questions/1950878/c-fo...

 
sizzlemctwizzle Scriptwright
FirefoxMacintosh

I love when people talk about loop optimization and use i++ in the for loop instead of ++i. It shows they truly don't understand the syntax of a for loop.

 
Piyush Soni Scriptwright
OperaWindows

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.

 
sizzlemctwizzle Scriptwright
FirefoxMacintosh

Piyush Soni wrote:
New compilers are intelligent enough to take care of that small ++i and i++ difference.
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:
And if we talk strictly about the syntax, both are correct.
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;) {}

 
Piyush Soni Scriptwright
FirefoxWindows

sizzlemctwizzle wrote:
Post-increment does something extra that's unnecessary and thus a pre-increment is syntactically the better choice.

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*.

 
sizzlemctwizzle Scriptwright
FirefoxMacintosh

Piyush Soni wrote:
if we talk *strictly* about syntax
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.

 
Piyush Soni Scriptwright
FirefoxWindows

Yes, I agree on that. Even if optimizations are turned on, it is always a good practice to use ++i in place of i++.