Mix string,replace vs regexp-exec vs string-match

JavaScript performance comparison

Test case created by 十年灯

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var astring = 'My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m ${age}. I have a dog named ${dog}My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m ${age}. I have a dog named ${dog}My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m ${age}. I have a dog named ${dog}My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m "${age}".My name is "${name}",I\'m ${age}. I have a dog named ${dog}';
  
  function matchMix(str, group) {
    var reg = /\$\{[^{}]+\}/gm;
    var strArr = str.split(reg);
    var labelArr = str.match(reg);
    var returnString = '',
      i = 0,
      label, len = labelArr.length;
    for (; i < len; i++) {
      label = labelArr[i].slice(2, -1);
      returnString += strArr[i] + (group[label] != null ? group[label] : '');
    }
    return returnString + strArr[i];
  }
  
  function mix(str, group) {
    return str.replace(/\$\{[^{}]+\}/gm, function(m, n) {
      n = m.slice(2, -1);
      return (group[n] != void 1) ? group[n] : '';
    })
  }
  
  function loopMix(str, group) {
    var reg = /\$\{[^{}]+\}/gm,
      res, returnString = '',
      start = 0,
      n;
    while (res = reg.exec(str)) {
      n = res[0].slice(2, -1);
      returnString += str.substring(start, res.index) + ((group[n] != undefined) ? group[n] : '');
      start = res.index + res[0].length;
    }
    return returnString + str.substr(start);;
  }
  
  function matchLoopMix(str, group) {
    var reg = /\$\{[^{}]+\}/gm;
    var labelArr = str.match(reg);
    var i = 0,
      label, len = labelArr.length;
    for (; i < len; i++) {
      label = labelArr[i].slice(2, -1);
      str = str.replace(labelArr[i], (group[label] != null ? group[label] : ''));
    }
    return str;
  }

};
</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(astring, {
  name: 'LIX',
  age: 11
})
pending…
loopMix,loop by regexp 'exec'
loopMix(astring, {
  name: 'LIX',
  age: 11
})
pending…
matchMix,use string's split & match and then to loop
matchMix(astring, {
  name: 'LIX',
  age: 11
})
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