Impact of string conversion on a string

JavaScript performance comparison

Revision 2 of this test case created by François REMY

Info

In this test case, I check whether which way of converting any input to a string for type safety reason has the least impact on the performance in case a string is passed as argument.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    window.a = function a(s) {
        return String(s).length;
    }
   
    window.b = function b(s) {
        return (""+s).length;
    }
   
    window.c = function c(s) {
       if(typeof(s)=="string") {
           return s.length;
       } else {
           return (""+s).length;
       }
    }
   
    window.d = function a(s) {
        return String(s).length;
    }
   
    window.e = function b(s) {
        return (""+s).length;
    }
   
    window.f = function c(s) {
        return (typeof(s)=="string")?s.length:(""+s).length;
    }
};
</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 function
window.tmp = a("Abc")==3
pending…
Empty string concatenation
window.tmp = b("Abc")==3
pending…
Conversion when needed only
window.tmp = c("Abc")==3
pending…
String function*
window.tmp = d("Abc")==3
pending…
Empty string concatenation*
window.tmp = e("Abc")==3
pending…
Conversion when needed only*
window.tmp = f("Abc")==3
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