Is it faster to use .hasClass() before removing classes, or just go ahead and remove it?
I'm not quite sure how to test this for myself, but I'm thinking this might be a rookie question, anyway.
Is it generally faster to test if an element has a class assigned to it before removing it? Or is that just doubling down on the processing time whether it's true or false, in which case it would be faster to just remove it without testing?
- if ($('[data-richcont]').hasClass('on'))
- $('[data-richcont]').removeClass('on');
And does the same stay true if I use
removeClass('on').addClass('off')?
If the question is confusing (it IS 3am while I'm typing), I'm thinking of how a regex like this would be slower because it runs the regex once if it fails, twice if it passes... so you might as well skip the
if() and just run it once:
- var text_match = /(<div [^>]+>)([\w-]+)<\/div>/gi;
- // this runs the same regex twice
- if (text_match.test(a))
- a = a.replace(text_match, '$2');
- // while this runs it once, and it only works if it matches anyway
- a = a.replace(text_match, '$2');