Correct vs. incorrect className contains
JavaScript performance comparison
Preparation code
<div id="testNode" class="foo bar baz">
</div>
<script>
var className = "className";
var spaces = /\s+/;
function stringToArray(s) {
if (typeof s === 'string' || s instanceof String) {
return s.trim().split(spaces);
}
// assumed to be an array
if (!s) {
return [];
}
return s.filter(function(x) {
return x;
});
}
function incorrect(node, classStr) {
return ((' ' + dom.byId(node)[className].trim() + ' ').indexOf(' ' + classStr.trim() + ' ') >= 0);
}
function correct(node, classStr) {
node = dom.byId(node);
classStr = classStr.trim();
if ((' ' + node[className] + ' ').indexOf(' ' + classStr + ' ') > -1) {
return true;
}
var classes = node[className].trim().split(spaces),
map = {};
for (var i = 0; i < classes.length; i++) {
map[classes[i]] = true;
}
classStr = stringToArray(classStr);
for (i = 0; i < classStr.length; i++) {
if (!(classStr[i] in map)) {
return false;
}
}
return true;
}
var dom = {
byId: function(node) {
if (typeof node !== 'string') {
return node;
}
return document.getElementById(node);
}
};
</script>
<script>
Benchmark.prototype.setup = function() {
var node = dom.byId('testNode');
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Incorrect (1 class name) |
|
pending… |
Correct (1 class name) |
|
pending… |
Incorrect (2 class names) |
|
pending… |
Correct (2 class names) |
|
pending… |
Correct (2 non-contiguous class names) |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments