.className vs getAttribute( 'class' )

JavaScript performance comparison

Test case created by ThinkingStiff

Preparation code

<div id="result" class="one two"></div>
<script>
Benchmark.prototype.setup = function() {
    Element.prototype.hasClass1 = function ( className )
    {
   
        return this.getAttribute( 'class' ).split( ' ' ).indexOf( className ) > -1;
           
    };
   
    Element.prototype.hasClass2 = function ( className )
    {
   
        return this.className.split( ' ' ).indexOf( className ) > -1;
   
    };
   
    var result = document.getElementById( 'result' );
   
   
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
.getAttribute( 'class' )
var hasClass = result.hasClass1( 'one' );
hasClass = result.hasClass1( 'three' );
pending…
.className
var hasClass = result.hasClass2( 'one' );
hasClass = result.hasClass2( 'three' );
pending…

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

Compare results of other browsers

0 comments

Add a comment