single-vs-multi-id

JavaScript performance comparison

Test case created

Preparation code

<style type="text/css">
.active {
   background: #ff0
}
</style>
<div class="fp_MB" id="fp_MB">
 <div class="fp_L"></div>
 <div class="fp_L"></div>
 <div class="fp_L"></div>
 <span></span>
</div>
<script type="text/javascript">
// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
    Object.defineProperty(String.prototype,'trim', {
        value: function() {
            return this.replace(/^\s+|\s+$/g,'');
        },
        writable:false,
        enumerable:false,
        configurable:false
    });
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
    value: function(c) {
        if(this.className.indexOf(c)<0) {
            this.className=this.className+=' '+c;
        }
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
    value: function(c) {
        this.className=this.className.replace(c,'').replace('  ',' ').trim();
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});

// hasClass, renamed so it won't conflict with jQuery's method
Object.defineProperty(Node.prototype, 'hasClass', {
    value: function (c) {
        return (this.className.indexOf(c) < 0);
    },
    writable: false,
    enumerable: false,
    configurable: false
});

</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
Single
document.getElementById('fp_MB').addEventListener('click', function() {
  if (document.getElementById('fp_MB').hasClass("active"))
    document.getElementById('fp_MB').addClass("active");
  else
    document.getElementById('fp_MB').removeClass("active");
}, false);
pending…
Multi
a = document.getElementById('fp_MB');

a.addEventListener('click', function() {
  if (a.hasClass("active"))
    a.addClass("active");
  else
    a.removeClass("active");
}, false);
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