Skip to content

Instantly share code, notes, and snippets.

@1Marc
Created July 25, 2011 05:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 1Marc/1103606 to your computer and use it in GitHub Desktop.
Save 1Marc/1103606 to your computer and use it in GitHub Desktop.
"But $.each is slow!" ..use fn arrEach and objEach then!!
// arrEach and objEach plugins
// code under MIT license by Marc Grabanski http://marcgrabanski.com
// jsperf tests: http://jsperf.com/each-vs-fn-arreach-and-objeach/2
$.arrEach = function(arr, cb){
for (var i = 0, item; item = arr[i]; ++i) {
cb.apply(item, [i, item]);
}
return arr;
}
$.fn.arrEach = function(cb){
return $.arrEach(this, cb);
}
// examples using array each
$.arrEach(["foo", "bar"], function(i, item){
console.log(i, item);
});
$(["foo", "bar"]).arrEach(function(i, item){
console.log(i, item);
});
// JSPerf results show mixed results of faster/slower for objEach, but huge gains for $.arrEach.
// This is why you test everything folks!!
$.objEach = function(obj, cb){
for (var i in obj) {
cb.apply(obj[i], [i, obj[i]]);
}
return obj;
}
$.fn.objEach = function(cb){
return $.objEach(this, cb);
}
// examples using object each
$.objEach({"foo":"bar", "baz":"bla"}, function(i, item){
console.log(i, item);
});
$({"foo":"bar", "baz":"bla"}).objEach(function(i, item){
console.log(i, item);
});
@rwaldron
Copy link

psst. You're leaking an i variable ;)

@1Marc
Copy link
Author

1Marc commented Jul 25, 2011

psst. You're leaking helpful pointers. Fixed.

@rwaldron
Copy link

:D anytime dude

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment