JavaScript Optimization – Destructive Vs Indexed Array Iteration

November 22, 2009 · 1 comment   115 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 4 Safari 4 Internet Explorer 8 FireFox 3
N= Normal
D = Destructive
N D N D N D N D
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!)

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. String Reversing Algorithm Performance In JavaScript
  3. Transpose An Array In JavaScript and jQuery
  4. Convert FusionCharts Data-XML To JavaScript Array
  5. Optimizing JavaScript (part 1)

{ 1 comment… read it below or add one }

1 Rohitesh Dutta November 22, 2009 at 18:58

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

Reply

Leave a Comment