case
4May/110

jQuery.quickEach

With jQuery, when you need to iterate all elements with a specific class for example, you use the each() method and inside the callback function you must convert the DOM element you receive as this to a jQuery object in order to access it's jQuery specific methods: $(this)
This is not such a big issue but if you have a lot of items and/or do this often, then times ads up. It would be a blast to have the this object directly as a jQuery instance. So here's a $ little plugin that does exactly that

Source website:
http://jsperf.com/jquery-each-vs-quickeach

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
jQuery.fn.quickEach = (function() {
  var jq = jQuery([1]);
  return function(c) {
   var i = -1,
       el, len = this.length;
   try {
    while (++i < len && (el = jq[0] = this[i]) && c.call(jq, i, el) !== false);
   } catch (e) {
    delete jq[0];
    throw e;
   }
   delete jq[0];
   return this;
  };
 }());

If you run the test on that page, on most browsers you'll see that quickEach() is about 80% faster than native each()

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


CommentLuv badge

*

No trackbacks yet.