JavaScript Optimization – Destructive Vs Indexed Array Iteration

November 22, 2009 · 2 comments   478 views

in Technical Publications

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:

  1. var test,
  2.    arr = ["item1", "item2", "item3", "item4", "item5"]
  3.  
  4. while(arr.length) {
  5.     test = arr.pop();
  6. }
  7.  

Destructive iteration works by “popping” elements from the array (much like a stack[1] ) 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:

  1. var test, length,
  2.     arr = ["item1", "item2", "item3", "item4", "item5"];
  3.  
  4. length = arr.length;
  5. while(length) {
  6.     test = arr[length–];
  7. }
  8.  

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 4Internet Explorer 8FireFox 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!)

Footnotes:

  1. Stack is a collection of data (like array) where items can be pushed in from one end and popped out from the same end. [top]

Related posts:

  1. Fast Algorithm To Find Unique Items in JavaScript Array
  2. Transpose An Array In JavaScript and jQuery
  3. String Reversing Algorithm Performance In JavaScript
  4. Convert FusionCharts Data-XML To JavaScript Array
  5. Optimizing JavaScript (part 1)
  • Rohitesh Dutta

    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? ;)

  • isko

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