Javascript for loop efficiency

后端 未结 5 590
我寻月下人不归
我寻月下人不归 2021-01-04 10:01

Is

for (var i=0, cols=columns.length; i

more efficient than

for (var i=0; i

        
相关标签:
5条回答
  • 2021-01-04 10:20

    Micro optimizations like this don't make huge sense in a language like Javascript unless you have tested and found the loop performance to be an issue.

    However, columns.length must be evaluated on each iteration because the number of columns may change during a loop iteration. Therefore storing the loop limit may give slightly better performance (but see my first point).

    0 讨论(0)
  • 2021-01-04 10:27

    Yes, it is. Accessing the length property wastes un-needed time (unless the array's length can change during iteration.).

    Here is how I loop through arrays: http://gist.github.com/339735

    0 讨论(0)
  • 2021-01-04 10:33

    The cached version is faster but, the 2nd version safer.

    If you're just curious about which loop types are fastest you may want to check this out: http://blogs.oracle.com/greimer/resource/loop-test.html

    0 讨论(0)
  • 2021-01-04 10:34

    Note that most of these loops require an additional statement in the loop to actually retrieve the i'th element from the array. You can avoid that and get a very fast loop with the following variant, which takes advantage of the fact that Javascript just returns undefined (which evaluates to false), if you access an array with an out of bounds index (rather than raising an error):

    for (var i = 0, col; col = columns[i]; ++i) { ... }

    Obviously this doesn't work if you're iterating through an array which contains elements which would evaluate to false.

    0 讨论(0)
  • 2021-01-04 10:38

    Any expression that's in the second portion of a for will be evaluated once per loop.

    So, here, with your second proposition, yes, columns.length will be calculated each time the condition is checked -- which would make the first proposition faster than the second one.


    (That's true for many other languages, btw)

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