classList vs addClass
JavaScript performance comparison
Info
Add 10 classes to 500 elements, then remove 1 class from the same 500 elements.
Preparation code
<script src="//code.jquery.com/jquery-git.js"></script>
<script>
var listStr = "alpha beta delta gamma epsilon zeta eta theta iota kappa",
thismany = 500,
$a = $(false),
$b = $(false);
while (thismany--) {
$a.push($('<div/>').appendTo('body')[0]);
$b.push($('<div/>').appendTo('body')[0]);
}
// Create functions to wrap up the behaviour that
// native classList would need to enforce to be
// equally tested against jQuery.
// jQuery allows for multiple classes
// to be passed as a string
$.fn.addToClassList = function(str) {
var classes = str.split(/\s/),
classLen = classes.length;
for (var e = 0; e < this.length; e++) {
for (var i = 0; i < classLen; i++) {
this[e].classList.add(classes[i]);
}
}
return this;
};
$.fn.removeFromClassList = function(str) {
var classes = str.split(/\s/),
classLen = classes.length;
for (var e = 0; e < this.length; e++) {
for (var i = 0; i < classLen; i++) {
this[e].classList.remove(classes[i]);
}
}
return this;
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
classList addClassToList |
|
pending… |
classList removeClassFromList |
|
pending… |
jQuery.fn.addClass |
|
pending… |
jQuery.fn.removeClass |
|
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:
- Revision 1: published by Rick Waldron
- Revision 2: published
0 comments