Correct vs. incorrect className contains

JavaScript performance comparison

Test case created by Bryan

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.

Testing in unknown unknown
Test Ops/sec
Incorrect (1 class name)
var classStr = 'bar';
incorrect(node, classStr);
pending…
Correct (1 class name)
var classStr = 'bar';
correct(node, classStr);
pending…
Incorrect (2 class names)
var classStr = 'bar baz';
incorrect(node, classStr);
pending…
Correct (2 class names)
var classStr = 'bar baz';
correct(node, classStr);
pending…
Correct (2 non-contiguous class names)
var classStr = 'baz bar';
correct(node, classStr);
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