String formatting

JavaScript performance comparison

Test case created by Sacha

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var text = 'Hello, my name is {0} {0} {1}!',
        result;
   
    String.prototype.format = function () {
      var string = this;
   
      for (var i = 0; i < arguments.length; i++) {
        string = string.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
      }
   
      return string;
    };
   
    String.prototype.format2 = function () {
      var string = this,
          i = 0,
          args = arguments.length;
   
      for (; i < args; i++) {
        string = string.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
      }
   
      return string;
    };
   
    String.prototype.format3 = function () {
      var string = this,
          args = arguments.length;
   
      while (args--) {
        string = string.replace(new RegExp('\\{' + args + '\\}', 'gm'), arguments[args]);
      }
   
      return string;
    };
};
</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
for
result = text.format('John', 'Mayer');
pending…
for2
result = text.format2('John', 'Mayer');
pending…
while
result = text.format3('John', 'Mayer');
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