i++ vs. ++i in a JavaScript for loop

2020-07-06 06:59发布

问题:

Because of JSLint, I almost always use i += 1 to increment a JavaScript for loop, but for quick and dirty scripts, I use i++ instead.
However, I see a lot of for loops in other people's code in which they increment i by doing ++i instead.

As far as I know, there is no difference in meaning between i++ and ++i, and jsPref shows no difference in performance.
As such, I'm wondering where the convention of doing ++i comes from and why people tend to do it.

Does anyone know why a lot of JS coders tend to prefer ++i over i++ when incrementing the counter in a for loop?
Thanks.

回答1:

In JS and PHP it does not make any difference, I think even in Java it does not make any difference but in pure c when compiler is not optimizing code it does, and that is why a lot of people use ++i because they are used to it from c.

EDIT: This is an answer for JS if you want history of pre and post increment searc C/C++ pre/post increment. Or see comments on @Orvev's answer.



回答2:

The difference is that i++ returns the value of i before incrementing and ++i the value of i after incrementing. There is no difference if you ignore the return value, e.g. in:

for (var i = 0; i < 10; i++) {

}

The habit of using ++i over i++ comes from C, where people were worried that storing the old value for i in i++ would incur a performance penalty.



回答3:

Way back in the day (we're talking IE6/7 here!), I recall benchmarking both forms and found that there was a small performance improvement with ++i instead of i++. My (unproven) theory was that a non-optimizing JS engine had to do a tiny bit more work in the i++ case: it had to save the previous value in case it would be used - and being a non-optimizing engine it didn't realize that the value would in fact not be used and didn't need to be saved.

However, with modern browsers there is no significant difference. If anything, i++ seems to be a tiny bit faster in many browsers.

Here are some tests of a variety of different loops:

http://jsperf.com/mikes-loops/5

Look for the results for "Traditional Loop" (this uses ++i) and "Traditional Loop with i++".

Regarding JSLint's requirement that one should never use ++i or i++ but only use i += 1 instead, that is simply insane and over-controlling, like so many other things in JSLint.

Personally I recommend JSHint instead. It is less dogmatic, much more practical, and easier to customize to your own style.



回答4:

There is a difference, however not when used in a for loop.

In an expression, i++ evaluates to the previous value of i, and then i is incremented. ++i increments first, and evaluates then.

For this reason, some programmers prefer to write ++i in their for-loops — either because they're used to it, or because they feel it is "more right" somehow.

edit: More probable is the solution Overv proposed: a relict from C.