regexp counting 2

JavaScript performance comparison

Revision 8 of this test case created by Isiah Meadows

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var largeCode = ""
  for (var i = 0; i < 1000000; i++) {
      largeCode += String.fromCharCode(Math.random() * 128 | 0)
  }
  function use(count) { window.count = count }
  
  function count1(str) {
      var re = /\n/g, count = 0
      while (re.test(str)) count++
      return count
  }
  
  function count2(str) {
      return str.split(/\n/g).length - 1
  }
  
  function count3(str) {
      var count = 0
      for (var i = 0; i < str.length; i++) {
          if (str.charCodeAt(i) === 0x0a) count++
      }
      return count
  }
  
  function count4(str) {
      var count = 0
      var i = 0
      while (true) {
          i = str.indexOf("\n", i) + 1
          if (i === 0) return count
          count++
      }
  }

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
split + length
use(count2(largeCode))
pending…
raw parser loop
use(count3(largeCode))
pending…
while regexp
use(count1(largeCode))
pending…
while + indexOf
use(count4(largeCode))
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.

0 Comments