Implementations of String.Format

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var strFormat = "{0}, {1}, {{2}}",
        values = ["abc", "as easy as", "123"],
        args = [strFormat].concat(values),
        trimRE = /^\s+|\s+$/g,
        digitRE = /\d+/,
        formatDigitRE = /{\d+}/g;
};
</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
Multiple Regular Expressiosn
function format(s, args) {
  if (!s) return "";

  args = [].slice.call(arguments, 1);
  var matches = s.match(formatDigitRE);
  if (matches) {
    for (var i = 0; i < matches.length; i++) {
      var index = parseInt(matches[i].match(digitRE), 10);
      if (args.length > index) {
        s = s.replace(matches[i], args[index]);
      }
    }
  }

  return s;
}
format.apply(format, args);
pending…
Single Regular Expression
function format(s, args) {
  args = [].slice.call(arguments, 1);
  return s.replace(/\{\{|\}\}|\{(\d+)\}/g, function(m, n) {
    if (m === "{{") {
      return "{";
    }
    if (m === "}}") {
      return "}";
    }
    return args[n];
  });
}
format.apply(format, args);
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