Is it faster to use .hasClass() before removing classes, or just go ahead and remove it?

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?

  1. if ($('[data-richcont]').hasClass('on'))
  2.       $('[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:

  1. var text_match = /(<div [^>]+>)([\w-]+)<\/div>/gi;

  2. // this runs the same regex twice
  3. if (text_match.test(a))
  4.       a = a.replace(text_match, '$2');

  5. // while this runs it once, and it only works if it matches anyway
  6. a = a.replace(text_match, '$2');