All pastes #1288935 Raw Edit

JavaScript for vs each vs map

public javascript v1 · immutable
#1288935 ·published 2008-12-19 00:47 UTC
rendered paste body
/*  * Performance test on "for", "$.each" and "$.map" (Firebug required) * * h3 ~ http://haineault.com * */var range = new Array(1000);var payload = function() { return 5*5*5; }// I had to wrap it in a anonymous functions,// without it Firebug refuse to profile it..console.profile('forloop');(function(){for (x=0; x < range.length; x++) { payload(); }})();console.profileEnd('forloop');console.profile('each');$.each(range, function(x){ payload(); });console.profileEnd('each');console.profile('map');$.map(range, function(x){ payload(); return true;});console.profileEnd('map');/*  * Results on my machine (time in millisecond): *  * 10 Iterations * ~~~~~~~~~~~~~ * +-------+-------+-------+ * |  for  | each  |  map  | * +-------+-------+-------+ * | 0.463 | 0.590 | 0.604 | * | 0.449 | 0.665 | 1.323 | * | 0.578 | 0.799 | 0.818 | * | 0.470 | 0.798 | 0.885 | * | 0.598 | 0.801 | 0.821 | * +-------+-------+-------+ * | 0.512 | 0.571 | 0.890 | * +-------+-------+-------+ * * 100 Iterations * ~~~~~~~~~~~~~~ * +-------+-------+-------+ * |  for  | each  |  map  | * +-------+-------+-------+ * | 5.543 | 2.974 | 3.169 | * | 4.006 | 8.726 | 8.028 | * | 3.288 | 6.963 | 6.779 | * | 5.341 | 9.314 | 5.892 | * | 1.696 | 3.141 | 3.407 | * +-------+-------+-------+ * | 3.975 | 6.223 | 5.455 | * +-------+-------+-------+ * * 1000 Iterations * ~~~~~~~~~~~~~~ * +-------+-------+-------+ * |  for  | each  |  map  | * +-------+-------+-------+ * | 39.50 | 80.34 | 68.76 | * | 11.79 | 22.05 | 20.34 | * | 32.60 | 56.24 | 72.08 | * | 65.23 | 61.22 | 57.64 | * | 30.84 | 61.44 | 56.23 | * +-------+-------+-------+ * | 36.07 | 56.25 | 55.01 | * +-------+-------+-------+*/