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

前端 未结 4 853
情书的邮戳
情书的邮戳 2021-02-14 21:23

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 se

相关标签:
4条回答
  • 2021-02-14 21:50

    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.

    0 讨论(0)
  • 2021-02-14 21:51

    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.

    0 讨论(0)
  • 2021-02-14 21:57

    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.

    0 讨论(0)
  • 2021-02-14 21:58

    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.

    0 讨论(0)
提交回复
热议问题