Cast To String

JavaScript performance comparison

Revision 11 of this test case created by caller

Info

Fastest way to cast to a string.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function t1(x) {
      return String(x);
    }
   
    function t2(x) {
      return new String(x);
    }
   
    function t3(x) {
      return x + '';
    }
   
    function t4(x) {
      return '' + x;
    }
   
    function t5(x) {
      return x.toString();
    }
   
    var o = {
      toString: function() {
        return "87";
      }
    };
};
</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
String Factory
t1(87)
pending…
String Instance
t2(87)
pending…
Pre Concat Empty String
t3(87)
pending…
Post Concat Empty String
t4(87)
pending…
Pre Concat Empty String from obj.toString
t3(o)
pending…
toString Method
t5(87)
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. Here’s a list of current revisions for this page:

0 comments

Add a comment