JavaScript Optimization – Destructive Vs Indexed Array Iteration

In number of JavaScript applications, developers are found to use destructive array iteration for the sake of readability and simplicity of codes. However, usage of the same is not always conducive towards the performance of the code.

An example of destructive array iteration:

var test,
   arr = ["item1", "item2", "item3", "item4", "item5"]; 

while(arr.length) {
    test = arr.pop();

Destructive iteration works by “popping” elements from the array (much like a stack ((Stack is a collection of data (like array) where items can be pushed in from one end and popped out from the same end.)) ) and in the process ultimately reducing its length to zero.

The method is clean, readable and can be well used in situations where the original array is no more required after iteration.

A very optimized “indexed” array iteration would look like:

var test, length,
    arr = ["item1", "item2", "item3", "item4", "item5"];
length = arr.length;
while(length) {
    test = arr[length--];

In the above scenario, the original array is simply traversed from the reverse end. This method of array traversal is very optimized for certain reasons as had been discussed in my post Optimizing JavaScript (part 1).

Profiling Results for the above two iteration methods

Browser: Chrome 4 Safari 4 Internet Explorer 8 FireFox 3
N= Normal
D = Destructive
10^3 1 1 1 1 3 4 1 1
10^4 1 2 1 2 9 18 1 3
10^5 3 7 3 8 83 170 4 13

The results are pretty evident that destructive iteration is costlier than other array iteration methods for JavaScript. (Also shows how horribly slow Internet Explorer is while processing simple JavaScript!)

2 Replies to “JavaScript Optimization – Destructive Vs Indexed Array Iteration”

  1. Hmmm… Maybe am from the C++/Java (as opposed to C) background, I prefer the indexed traversal. Never really wondered about the cost, though! Lucky by accident? 😉

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.