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

前端 未结 4 865
情书的邮戳
情书的邮戳 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: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.

提交回复
热议问题