jQuery CSS vs addClass speed (v5)

Revision 5 of this benchmark created by Jason on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style type="text/css">
.newClass {
background-color:red;
}

.otherClass {
background-color: green;
}
</style>

<div id="c1"><div class="otherClass">Hi</div></div>

Setup

var precache =$('.otherClass');

Teardown


    $('#c1').replaceWith('<div id="c1"><div class="otherClass">Hi</div></div>');
  

Test runner

Ready to run.

Testing in
TestOps/sec
Remove and Add class
$('.otherClass').removeClass('otherClass').addClass('newClass');
ready
Apply CSS
$('.otherClass').css({
  'background-color': 'red'
});
ready
Add Class
$('.otherClass').addClass('newClass');
ready
Plain JS Replace Class
var elem = document.getElementById('c1').childNodes[0];
elem.setAttribute('class', elem.getAttribute('class').replace('otherClass', 'newClass'));
ready
Plain JS Replace Class v2
var elem = document.getElementById('c1').childNodes[0];
elem.className = elem.className.replace('otherClass', 'newClass');
ready
classList api add+rem
var elem = document.getElementById('c1').childNodes[0];
elem.classList.remove('otherClass');
elem.classList.add('newClass');
ready
jQuery Replace Class v2
var elem = $('#c1')[0].childNodes[0];
elem.className.replace('otherClass', 'newClass');
ready
jQuery Replace Attr
var elem = $('#c1 div')
elem.attr("class", elem.attr("class").replace('otherClass', 'newClass'));
ready
jQuery select pure JS add class
$('.otherClass')[0].classList.add('newClass');
ready
precache jquery to pure js
precache[0].classList.add('newClass');
ready
precache jquery
precache.addClass('newClass');
ready
precache jquery to pure js replace
precache[0].className.replace('otherClass', 'newClass');
ready

Revisions

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