insert into string after substring

JavaScript performance comparison

Test case created by zoom

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var colgroups = new Array(25000),
        cl = colgroups.length;
    for (var i = 0; i < cl; i++) {
      colgroups[i] = '<col' + i + '>';
    }
    var delimp = /(<table[^>]*>)/g;
    var start = "<table";
    var stop = ">";
    var startl = start.length;
    var stopl = stop.length;
    var foo = '<table><foo/></table><table bar="bar"><foo/></table>loremipsum<table>blaaah</table>';
    for (var i = 0; i < 10; i++) {
      foo += foo;
    }
    var bar = '<table><foo/></table><table bar="bar"><foo/></table>loremipsum<table>blaaah</table>';
   
    function insertColgroup(str, index, start, startl, stop, stopl, colgroups) {
      var i = str.indexOf(start);
      if (i === -1 || str === "") return str;
      i = str.indexOf(stop, i + startl);
      var j = i + stopl;
      return i === -1 ? str : str.substring(0, j) + colgroups[index] + insertColgroup(str.substring(j), ++index, start, startl, stop, stopl, colgroups);
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
split & join w/ regexp
var arr = foo.split(delimp),
    l = arr.length,
    c = 0;
for (var i = 0; i < l; i++) {
  if (arr[i].lastIndexOf(start, 0) === 0) {
    arr[i] += colgroups[c++];
  }
}
arr.join('');
pending…
recursive indexof
insertColgroup(foo, 0, start, start.length, stop, stop.length, colgroups);
pending…
indexof while loop
var bar = "";
var index = 0, c = 0, i;
do
{
        i = foo.indexOf(start, index);
        i = i === -1 ? i : foo.indexOf(stop, i+startl);
        bar += i === -1 ? foo.substring(index) : foo.substring(index, i+stopl) + colgroups[c++];
        index = i+stopl;
}
while (i !== -1);
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