Fast way to join a complex HTML string.

JavaScript performance comparison

Test case created by 十年灯

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function mix(str, group) {
    str = str.replace(/\$\{([^{}]+)\}/gm, function(m, n) {
      return (group[n] != undefined) ? group[n] : '';
    })
    return str;
  }
  
  function loopMix0(str, group) {
    var reg = /\$\{([^{}]+)\}/gm,
      res;
    while (res = reg.exec(str)) {
      str = str.substr(0, res.index) + ((group[res[1]] != undefined) ? group[res[1]] : '') + str.substr(res.index + res[0].length);
    }
    return str;
  }
  
  function loopMix1(str, group) {
    var reg = /\$\{([^{}]+)\}/gm,
      res, returnString = '',
      start = 0;
    while (res = reg.exec(str)) {
      returnString += str.substring(start, res.index) + ((group[res[1]] != undefined) ? group[res[1]] : '');
      start = res.index + res[0].length;
    }
    returnString += str.substr(start);
    return returnString;
  }
  
  function loopMix2(str, group) {
    var reg = /\$\{([^{}]+)\}/gm,
      res, returnString = '',
      start = 0;
    while (res = reg.exec(str)) {
      returnString += str.substring(0, res.index) + ((group[res[1]] != undefined) ? group[res[1]] : '');
      start = res.index + res[0].length;
      str = str.substr(start);
      // console.log(str)
      reg.lastIndex = 0;
    }
    returnString += str;
    return returnString;
  }

};
</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
mix, use string's replace+RegExp
mix('My name is ${name},I\'m ${age}.', {
  name: 'LIX',
  age: 11
})
pending…
loopMix0,loop regexp 'exec'
loopMix0('My name is ${name},I\'m ${age}.', {
  name: 'LIX',
  age: 11
})
pending…
loopMix1
loopMix1('My name is ${name},I\'m ${age}.', {
  name: 'LIX',
  age: 11
})
pending…
loopMix2
loopMix2('My name is ${name},I\'m ${age}.', {
  name: 'LIX',
  age: 11
})
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