I ++ vs. ++ I'm in a JavaScript loop

Because of JSLint, I almost always use i += 1

JavaScript for loop to grow, but for quick and dirty scripts I use i++

instead.
However, I see a lot for loops in other people's code in which they increment i

by doing instead ++i

.

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 fulfillment agreement comes from ++i

and why people tend to do it.

Does anyone know why many JS coders prefer ++i

over i++

when incrementing a counter in a for loop?
Thank.

+3


source to share


4 answers


In JS and PHP it doesn't make any difference, I think even in Java it doesn't make any difference, but in pure c when the compiler doesn't optimize the code it does and that's why a lot of people use ++ me because they are used to it with c.



EDIT: This is the answer for JS if you want pre / post backstory to increment. Or see the comments on @Orvev's answer.

+2


source


The difference is that it i++

returns the value i

before incrementing and the ++i

value i

after incrementing. It makes no difference if you ignore the return value, for example. in:

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

}

      



The habit of using ++i

over i++

comes from C, where people were concerned that keeping the old value for i

in i++

would lead to poor performance.

+7


source


Going back (we're talking IE6 / 7 here!), I remember comparing both forms and found that ++i

there was a slight performance improvement instead i++

. My (unproven) theory was that a suboptimal JS engine should have done a little less work in case i++

: it should have retained the previous value in case it was used - and, being a non-optimizing engine, it didn't realize that the value will not actually be used and does not need to be preserved.

However, there is no significant difference with modern browsers. Anyway, i++

appears to be slightly faster in many browsers.

Below are some tests of different loops:

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

Look for results for "Traditional Loop" (this uses ++i

) and "Traditional Loop with i ++".

As far as requiring JSLint to never use ++i

or i++

but only use instead i += 1

, it is just insane and overcontrolled, like so many other things in JSLint.

I personally recommend JSHint . It's less dogmatic, much more practical, and easier to customize in your own style.

+4


source


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

The expression i++

evaluates the previous value i

and then i

increments. ++i

first increases and then evaluates.

For this reason, some programmers prefer to write ++i

in their for-loops - either because they are used to it or because they feel it is "more correct" in some way.

edit: More likely solution is Overv: relic from C.

+2


source







All Articles