views:

265

answers:

6

Let's imagine we should get some data...

var data = [];

//some code omitted that might fill in the data (though might not)

Then we need to do something with the data. And my question is how to do it more effectively. Like so?:

if (data.length) {
    for (var i = 0; i < data.length; i++) {
        //iterate over the data and do something to it
    }
}

Or just like so?:

for (var i = 0; i < data.length; i++) {
    //iterate over the data and do something to it
}

The point is whether to check the length before iterating or not?

+2  A: 

What is the need to check data.length and iterate it?

Simply using for loop would do.

Kunal
+4  A: 

I believe the second version is more idiomatic, not just in JavaScript, but in most programming languages. If you're that concerned about timing, you could save the length of the array in a variable, and use that variable in the loop, but I don't think that's necessary:

var data = [];
var length = data.length;
for (var i = 0; i < length; i++) {
    //iterate over the data and do something to it
}
Khnle
length is not a method; it's a property. So I guess there is no point to save it elsewhere.
Alex Polo
yes, you're right. Ignore that.
Khnle
caching the length actually can help performance, as it results in less lookups for the same value each time. you can simplify it further as follows: `for (var i = 0, j = data.length; i < j; i++) ...`
Funka
+1  A: 

If data has no items, then the data.lenght will be 0. Thus your loop will never fire as i = 0 is already less than the number of items in the array. Therefore, option 2 is fine.

However, in doing managed code, you probably would want to check for a NULL object before calling .length on that object.

Tommy
+2  A: 

I usually don't check the length before iteration. As a matter of fact, the for loop itself will check the length on each iteration.

There's no performance overhead worth mentioning. In case length was = 0, the only extra instruction would be that a new int i would be declared in the memory. You need thousands of those to feel a millisecond impact.

SiN
+1  A: 

I think the most efficient way to loop over data in this case would be:

var pos = data.length;
while (pos--) {
  // do something to => data[pos]
}

, minimizing lookups and declarations as much as possible. It will iterate over the items backwards, but that might not always be of concern.

npup
"Apparently the removal of the simple condition used to test when to end the loop makes most of the difference, and the fact that you do –i instead of i– also accords for some." - http://codeutopia.net/blog/2009/04/30/optimizing-javascript-for-extreme-performance-and-low-memory-consumption/
Alex Polo
I have a thing for using the prefix variant when I can, but `--pos` wouldn't work here here I'm afraid (would be looking at the wrong index in the block). And I think it would matter when programming in for example C, but not Javascript (at least I don't remember seeing any difference when I tested it - ages ago).
npup
+8  A: 

I don't think it's worth checking whether to execute the for loop based on the length of data as it probably won't make much difference performance-wise if the for loop is only executed a few times.

But generally it is faster to get the length first rather than putting it as i<data.length as it'll need to access the variable each time. As for which way is the most efficient to loop through data, different browsers are optimized for different kinds of loops. However, it's only IE which is seriously slow (orders of magnitude slower than other browsers in the below tests) so I think optimizing for other browsers may not be worth it.

Here's the results for the following benchmarks (the fastest indicated by + and slowest indicated by -):

           FF      Chrome  Safari  Opera   IE6      IE7      IE8 
Method 1  +0.163+  0.221   0.246   0.269  -11.608- -12.214- -7.657-
Method 2   0.175  +0.133+  0.176  +0.147+   8.474    8.752   3.267
Method 3   0.206   0.235   0.276   0.245    8.002    8.539   3.651
Method 4   0.198   0.372   0.447   0.390   +6.562+  +7.020+  2.920
Method 5   0.206   0.372   0.445  -0.400-   6.626    7.096  +2.905+
Method 6   0.176   0.167  +0.175+  0.223    7.029    8.085   3.167
Method 7  -0.263- -0.567- -0.449-  0.413    6.925    7.431   3.242

Method 1: Using "standard" for loops:

for (var i=0; i<data.length; i++) {
    var x = data[i]
}

Method 2: Using "standard" for loops, assigning length so it doesn't have to access each time:

for (var i=0, len=data.length; i<len; i++) {
    var x = data[i]
}

Method 3: This is similar to the method jQuery uses in $.each(). Note the assigning to len so that it doesn't have to get the length every time.

for (var x=data[0], len=data.length, i=0; i<len; x=data[++i]) {}

Method 4: Using while loops, going forwards. WARNING: needs each item in the array to evaluate to true, i.e. not false, 0, null, undefined, '' etc!

var x, i=0
while (x = data[i++]) {}

Method 5: The same as method 4, only using for to do the same:

for (var x,i=0; x=data[i++];) {}

Method 6: Looping through the loop backwards using while:

var i = data.length
while (i--) {
    var x = data[i]
}

Method 7: Using method 4/method 5, but without needing items to evaluate to true, replacing x = data[i++]:

var x, i=0, len=data.length
while ((x=data[i++]) || i<len) {}

This first checks whether data[i++] evaluates to true then checks whether it's the last item so it can have similar performance in IE with fewer problems with null and false etc in the arrays. Note that when using while vs for in this case there wasn't a noticeable difference, but I prefer while as I think it's more clear.

I generally don't like to optimize unless there's a specific long-running task as it often comes at a cost of readability - please only do it if you've got a specific case where you've got lots of data to load etc :-)

EDIT: Because methods 4/5 were so fast on IE, added a version with fewer side effects.

EDIT 2: Redid all of the tests, this time without any browser extensions and over a longer period of time. Here's the code for the sake of completeness (sorry for making this post so long:)

function Tmr() {
    this.tStart = new Date()
}

Tmr.prototype = {
    Time: function() {
        var tDate = new Date()
        var tDiff = tDate.getTime() - this.tStart.getTime()
        var tDiff = tDiff / 1000.0 // Convert to seconds
        return tDiff
    }
}

function normalfor(data) {
    for (var i=0; i<data.length; i++) {
        var x = data[i]
    }
}

function fasterfor(data) {
    for (var i=0, len=data.length; i<len; i++) {
        var x = data[i]
    }
}

function jqueryfor(data) {
    for (var x=data[0], len=data.length, i=0; i<len; x=data[++i]) {

    }
}

function whileloop(data) {
    var x, i=0
    while (x = data[i++]) {

    }
}

function fixedwhileloop(data) {
    var x, i=0, len=data.length
    while ((x=data[i++]) || i<len) {

    }
}

function forwhileloop(data) {
    for (var x,i=0; x=data[i++];) {

    }
}

function fixedforwhileloop(data) {
    for (var x,i=0,len=data.length; (x=data[i++])||i<len; ) {

    }
}

function whilebackwards(data) {
    var i = data.length
    while (i--) {
        var x = data[i]
    }
}

var undefined
var NUMTIMES = 1000000
var data = '$blah blah blah blah blah|'.split('')

function test() {}
function getfntime(fn) {
    // Get the rough time required when executing one of the above functions
    // to make sure the `for` loop and function call overhead in `run` doesn't 
    // impact the benchmarks as much
    var t = new Tmr()
    for (var xx=0; xx<NUMTIMES; xx++) {
        fn()
    }
    return t.Time()
}
var fntime = getfntime(test)

function run(fn, i){
    var t = new Tmr()
    for (var xx=0; xx<NUMTIMES; xx++) {
        fn(data)
    }
    alert(i+' '+(t.Time()-fntime))
}

setTimeout('run(normalfor, "1:normalfor")', 0)
setTimeout('run(fasterfor, "2:fasterfor")', 0)
setTimeout('run(jqueryfor, "3:jqueryfor")', 0)
setTimeout('run(whileloop, "4:whileloop")', 0)
setTimeout('run(forwhileloop, "5:forwhileloop")', 0)
setTimeout('run(whilebackwards, "6:whilebackwards")', 0)
setTimeout('run(fixedwhileloop, "7:fixedwhileloop")', 0)
//setTimeout('run(fixedforwhileloop, "8:fixedforwhileloop")', 0)
David Morrissey
Nice collection of methods, and good explanations!
gnarf
I didn't even know that jQuery managed it in such an ugly way. (I believe there might be some reason.)
Alex Polo
BTW, good bunch of methods! Regards!
Alex Polo
@David Maricone: From jQuery itself: `A special, fast, case for the most common use of each` (it's only for going `$.each(array, fn)` not `$('blah').each(fn)` as far as I can tell.) I suppose it doesn't matter what it looks like so long as the code written by it's users is clean and relatively fast :-)
David Morrissey
Also, to mention an extra method, the do...while loop can be used. Though there isn't much difference I guess.
Alex Polo
The problem with the `do...while` loop is that the code will be executed *at least* once, which is very uncommon. You would need to check the `length` of `data` if you used it (`do...while` is roughly equivalent to `statements; while (condition) {statements;}`) it is slightly faster, but only because it doesn't execute the first condition :-)
David Morrissey
Nice comparison, but are you sure the `0.008` in FF's method 4 is correct? It's a large difference from the other methods…
Marcel Korpel
@Marcel Korpel: Thanks for pointing this out! I ran it multiple times and it gave the same result a while ago, but I can't seem to reproduce it now. Ah well, I'll repost all the benchmarks, this time with *all extensions disabled* in all the browsers and run over a larger time period (with the "script running slowly" dialogs disabled.) I'll also post the actual code for people to debate my methods :-P
David Morrissey
@Marcel Korpel: It looks like Firebug slows down Firefox by a factor of 10x in most cases :-P
David Morrissey
It's really sad how much slower IE is... every other browser, no matter how you loop is sub-second. IE's best, by far, in it's latest browser, is just shy of 3 seconds...
Chad
@Chad: It's even more sad the way that IE7 was actually slower than IE6, though it's much faster in IE8 (way short of other browsers though.) Here's hoping for IE9 :-)
David Morrissey
Interesting, especially the use of Firebug (though this is only one aspect of JavaScript, I hope a lot of other things, like DOM-building, aren't affected *that* much by it). BTW, I tested this myself with Firefox some time ago and my results differed slightly, it was more like http://blogs.sun.com/greimer/entry/best_way_to_code_a (where your method 6 was the fastest).
Marcel Korpel