jquery addClass and hasClass vs add attribute and css

JavaScript performance comparison

Test case created by Mohit Seth

Info

This test case is checking the class of div. If it exists, remove it and add a seperate style.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<div id="test" class="open" opened="true">Test</div>

<style>
  open{color:green;}
  closed{color:red;}
</style>
 
<script>
Benchmark.prototype.setup = function() {
    var $test = $("#test");
   
};
</script>

Preparation code output

Test

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
addClass
if($test.hasClass('open')){
   $test.removeClass('open').addClass('closed');
}

else{
  $test.removeClass('closed').addClass('open');
}
pending…
attr and inline style
if($test.attr('opened')){
   $test.css('color','red').attr('opened',false);
}
else{
   $test.css('color','green').attr('opened',true);
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment