Y.Array.each vs. forEach vs. for vs. for-in

JavaScript performance comparison

Revision 5 of this test case created

Info

Do a comparison of - YUI's Y.Array.each - native forEach loop - native for loop - native for loop w/ length variable - native for-in loop - native while loop

Preparation code

<script type="text/javascript" src="//yui.yahooapis.com/combo?3.7.3/build/yui/yui-min.js"></script>
<script>
  var iterations = 30;
  var arr = [];
  var sum = 0;
  var i = 0;
 
  while (i < iterations) {
   arr.push(i++);
  }
 
  Y = YUI().use('lang');
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Y.Array.each
Y.Array.each(arr, function(v) {
 sum += v;
});
pending…
Native forEach loop
arr.forEach(function(v) {
  sum += v;
});
pending…
Native for loop
for (var i = 0; i<arr.length; i++) {
  sum += arr[i];
}
pending…
Native for loop w/ length variable
for (var i = 0, len = arr.length; i < len; i++) {
 sum += arr[i];
}
pending…
Native for-in loop
for (var i in arr) {
  sum += arr[i];
}
pending…
Native while loop
var item;
while (item = arr.shift()){
  sum += item;
}
pending…
var item;
while(item = Array.prototype.shift.call(arr)){
   sum += item;
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment