className.search vs regex

JavaScript performance comparison

Test case created by Josh Rhoades

Preparation code

<div id="test" class="testOne testTwo testThree"></div>
<div id="test1" class="testOne"></div>
<div id="test2" class=" testOne "></div>
<div id="test0" class=""></div>
<script>
Benchmark.prototype.setup = function() {
    var elTest = document.getElementById('test');
    var elTest1 = document.getElementById('test1');
    var elTest2 = document.getElementById('test2');
    var elTest0 = document.getElementById('test0');
};

Benchmark.prototype.teardown = function() {
    elTest = elTest1 = elTest2 = null;
};
</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
className.search
if (elTest.className.search('testOne') >= 0) {
  //has class
  console.log('div#test has Class');
} else {
  console.log('div#test has No Class');
}
if (elTest1.className.search('testOne') >= 0) {
  //has class
  console.log('div#test1 has Class');
} else {
  console.log('div#test1 has No Class');
}
if (elTest2.className.search('testOne') >= 0) {
  //has class
  console.log('div#test2 has Class');
} else {
  console.log('div#test2 has No Class');
}
if (elTest0.className.search('testOne') >= 0) {
  //has class
  console.log('div#test0 has Class');
} else {
  console.log('div#test0 has No Class');
}
pending…
regex
if ((" " + elTest.className + " ").replace(/[\t\r\n]/g, " ").indexOf('testOne') >= 0) {
  //has class
  console.log('div#test has Class');
} else {
  console.log('div#test has No Class');
}
if ((" " + elTest1.className + " ").replace(/[\t\r\n]/g, " ").indexOf('testOne') >= 0) {
  //has class
  console.log('div#test1 has Class');
} else {
  console.log('div#test1 has No Class');
}
if ((" " + elTest2.className + " ").replace(/[\t\r\n]/g, " ").indexOf('testOne') >= 0) {
  //has class
  console.log('div#test2 has Class');
} else {
  console.log('div#test2 has No Class');
}
if ((" " + elTest0.className + " ").replace(/[\t\r\n]/g, " ").indexOf('testOne') >= 0) {
  //has class
  console.log('div#test0 has Class');
} else {
  console.log('div#test0 has No Class');
}
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