Removing by split vs. Removing by replace

JavaScript performance comparison

Test case created

Preparation code

<div id="btn" class="btn btn-main btn-download hidden enabled"></div>
<script>
Benchmark.prototype.setup = function() {
    var oElement = document.getElementById( 'btn' );
};
</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
Remove by split
var removeClassBySplit = function( oElement, sClassname )
{
        var sWhitespace         = ' ',
                aClasses                = oElement.className.split( sWhitespace ),
                aNewClasses             = [],
                sClass,
                nCount                  = 0,
                nClassesLength  = aClasses.length;

        for ( ; nCount < nClassesLength; ++nCount )
        {
                sClass = aClasses[nCount];

                if ( sClass && sClass !== sClassname && sClass !== sWhitespace )
                {
                        aNewClasses.push( sClass );
                }
        }

        oElement.className = aNewClasses.join( sWhitespace );

        sWhitespace = aClasses = aNewClasses = sClass = nCount = nClassesLength = null;
};

removeClassBySplit( oElement, 'btn' );
removeClassBySplit( oElement, 'hidden' );
removeClassBySplit( oElement, 'enabled' );
pending…
Remove by replace
var removeClassByReplace = function( oElement, sClassname )
{
        oElement.className = oElement.className.replace( sClassname, '' );
};

removeClassByReplace( oElement, 'btn' );
removeClassByReplace( oElement, 'hidden' );
removeClassByReplace( oElement, 'enabled' );
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