jQuery hasClass vs. addClass and removeClass (v9)

Revision 9 of this benchmark created on


Description

Test the performance of toggling classes in jQuery vs. checking if a class exists before (possibly unnecessary) manipulation.

Preparation HTML

<div class="test blue"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Test runner

Ready to run.

Testing in
TestOps/sec
hasClass + removeClass
var $test = $('.test');
if ($test.hasClass('blue')) { $test.removeClass('blue'); }
ready
removeClass
var $test = $('.test');
$test.removeClass('blue');
ready
hasClass only
var $test = $('.test');
$test.hasClass('blue');
ready
asdasdasd
var $test = $('.test.blue');
$test.removeClass('blue');
ready

Revisions

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