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 4 | Safari 4 | IE 8 | FF 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!)
Run your this benchmark on your own browser: https://jsbench.me/0elxx6rvvc/1


Leave a reply to Rohitesh Dutta Cancel reply