Add and remove class names

Benchmark created by Andrew Hedges on


Description

Just seeing if it's possible to optimize the addClass and removeClass functions from Thomas Fuchs' very cool Zepto JavaScript mini-framework.

Preparation HTML

<p id="el" class="big blue">A DOM element with a className attribute.</p>
<script>
  // zepto
  
  function classRE(name) {
   return new RegExp("(^|\\s)" + name + "(\\s|$)");
  }
  
  function addClass(el, name) {
   return !classRE(name).test(el.className) && (el.className += (el.className ? ' ' : '') + name);
  }
  
  function removeClass(el, name) {
   return el.className = el.className.replace(classRE(name), ' ').replace(/^\s+|\s+$/g, '');
  }
  
  // zepto 2
  
  function addClass2(el, name) {
   return !classRE(name).test(el.className) && (el.className += ' ' + name).replace(/^\s+/g, '');
  }
  
  function removeClass2(el, name) {
   return el.className = el.className.replace(classRE(name), '');
  }
  var el = document.getElementById('el');
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Zepto
addClass(el, 'italic');
removeClass(el, 'italic');
ready
Zepto 2
addClass2(el, 'italic');
removeClass2(el, 'italic');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Andrew Hedges on