Posted By

jschilling on 04/27/09


Tagged

array optimization javscript


Versions (?)

forEach function - fastest loop iteration


 / Published in: JavaScript
 

URL: http://www.six-degrees.com/six-degrees.html

hope you enjoy - thanks to Tom Duff (for implementation in C), Dean Edwards, and Nicholas Zakas for the idea

  1. forEach = (function()
  2. {
  3. /**
  4. * USAGE
  5.   * instead of:
  6.   * for(var i=0, il=some.length; i<il; i++)
  7.   * Use this:
  8. * forEach(object, function(i){
  9. * i.doSomething();
  10. * }, context);
  11.   *
  12.   * or this:
  13.   * forEach(object, function(i){
  14.   * i.doSomething();
  15.   * });
  16.   *
  17. * @param object elementNodeList || array
  18. * @param block function
  19. * @param context inherited by the this object
  20. */
  21. return function(object, block, context)
  22. {
  23. var len = Math.floor(object.length / 4),
  24. left = object.length % 4, i = 0;
  25. if(left > 0){
  26. do {
  27. block.call(context, object[i++], i, object);
  28. } while (--left > 0);
  29. };
  30. while(len-- > 0)
  31. {
  32. block.call(context, object[i++], i, object);
  33. block.call(context, object[i++], i, object);
  34. block.call(context, object[i++], i, object);
  35. block.call(context, object[i++], i, object);
  36. };
  37. };
  38. })();

Report this snippet  

You need to login to post a comment.