improved performance of 'hasClass' method

View: New views
2 Messages — Rating Filter:   Alert me  

improved performance of 'hasClass' method

by Matt-184 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I was profiling code on one of my projects and realized that a lot of
time was being spent in the 'hasClass' method. I tinkered with it a
little bit and was able to reduce the run-time of the method by about
a third. Here are my changes to 'hasClass':

-----------------------------------

hasClass: function(el, className) {
        var re = el.className.split(' ');
        var f = function(el) {
                return -1 != re.indexOf(className);
        };
        return Y.Dom.batch(el, f, Y.Dom, true);
},

-----------------------------------

Is there a reason that you are using regular expressions as apposed to
 the above method? Is there a case where the Regex is faster?

thanks
-matt

here are my numbers:
http://spreadsheets.google.com/ccc?key=pJL0oH5TVaRjjog0qePS2bQ&hl=en_US

here is additional explaination:
http://mattsnider.com/?p=28


Re: improved performance of 'hasClass' method

by Matt Sweeney :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi Matt,

Of A-grade browers, The Array.indexOf method is only implemented in Firefox.

The next version of Dom includes some performance enhancements,
including a faster hasClass method that caches regexes so subsequent
tests for the same className are faster.

 From my testing, a cached regex is generally faster than str.indexOf
tests for a long loop.

Matt

Matt wrote:

> I was profiling code on one of my projects and realized that a lot of
> time was being spent in the 'hasClass' method. I tinkered with it a
> little bit and was able to reduce the run-time of the method by about
> a third. Here are my changes to 'hasClass':
>
> -----------------------------------
>
> hasClass: function(el, className) {
> var re = el.className.split(' ');
> var f = function(el) {
> return -1 != re.indexOf(className);
> };
> return Y.Dom.batch(el, f, Y.Dom, true);
> },
>
> -----------------------------------
>
> Is there a reason that you are using regular expressions as apposed to
>  the above method? Is there a case where the Regex is faster?
>
> thanks
> -matt
>
> here are my numbers:
> http://spreadsheets.google.com/ccc?key=pJL0oH5TVaRjjog0qePS2bQ&hl=en_US
>
> here is additional explaination:
> http://mattsnider.com/?p=28
>
>
>
>  
> Yahoo! Groups Links
>
>
>
>
>