JavaScript Optimisation – 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) 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 optimised “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 4Safari 4IE 8FF 3
N= Normal
D = Destructive
NDNDNDND
10^311113411
10^4121291813
10^5373883170413

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!)

Run your this benchmark on your own browser: https://jsbench.me/0elxx6rvvc/1

2 responses

  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? 😉

    Like

  2. <code>
    test = arr[length–];
    </code>
    is it not supposed to be this?
    test = arr[length–-];

    Like

Leave a reply to isko Cancel reply