Tuesday, 1 July 2014

Javascript: Iteration speed test ($.grep for teh win!)

So +Mehdi Rahman and I were trying to work out which was fastest... turns out $.grep wins and the for loop and the $.each perform differently on Chrome and FireFox. Quite a lot differently!


var start = new Date().getTime();
for (b = 0; b < 50000; ++b) {
 var a = ["1","2","1","2","1","2","1","2","1","2"];
 for(var i = 0; i < a.length; i++){
  if(a[i] === "1"){
   a.splice(i, 1);
  }
 }
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

var start = new Date().getTime();
for (b = 0; b < 50000; ++b) {
 var a = ["1","2","1","2","1","2","1","2","1","2"];
 $.each(a, function(k, v){
  if(v){
   if(v === "1"){
    a.splice(k, 1);
   }
  }else{
   return false
  }
 });
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

var start = new Date().getTime();
for (b = 0; b < 50000; ++b) {
 var a = ["1","2","1","2","1","2","1","2","1","2"];
 $.grep(a, function( n, i ) {
  return ( n !== "1" );
 });
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

No comments:

Post a Comment