Dirk Smaverson
Dirk Smaverson

Reputation: 873

what are some drawbacks to using clone & pop to iterate through an array rather than using a for loop?

it looks like this method of iteration is much much faster than a for loop:

var arr = window.arr.slice(0),
    fruit = arr.pop();
while (fruit) {
 fruit = list.pop();
}

as evidenced in this jsperf test: http://jsperf.com/loop-iteration-length-comparison-variations/7

I know I'm taking a memory hit by cloning the array but if i delete the clone right after i loop through it, what else should i be weary of?

Upvotes: 0

Views: 65

Answers (1)

RobG
RobG

Reputation: 147453

The main drawback is here:

fruit = arr.pop();
while (fruit) {

If fruit evaluates to false (i.e. is null, undefined, 0, and so on) the loop will stop. That is nasty for sparse arrays, e.g.

var arr = [0,,,,2];

will only loop over the last member, then attempt to evaluate arr[arr.length - 2], find it returns undefined (it doesn't exist) so the loop ends. This is avoidable in a for loop as you can test if the property exists first (if necessary):

for (var i=0, iLen=arr.length; i<iLen; i++) {

  if (i in arr) {
    // arr has a property i so do stuff with arr[i]
  }
}

So the pop method might be fast, but can only be reliable if you are certain that none of the values evaluate to false, or the loop is terminated by keeping a counter:

var fruit, 
    i = arr.length;
do {
  fruit = arr.pop();
} while (--i)

so you might as well do

do {
  fruit = arr[--i];
} while (i);

and not bother with the copy.

Upvotes: 2

Related Questions