Cast To String

JavaScript performance comparison

Revision 6 of this test case created by Nicolás

Info

Fastest way to cast to a string on an object that may be null or undefined.

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
var u, n = null,
    i = 87,
    s = 'tacos',
    b = true,
    u2, n2, i2, s2, b2;
u2 = String(u);
n2 = String(n);
i2 = String(i);
s2 = String(s);
b2 = String(b);
pending…
String Constructor
var u, n = null,
    i = 87,
    s = 'tacos',
    b = true,
    u2, n2, i2, s2, b2;
u2 = new String(u);
n2 = new String(n);
i2 = new String(i);
s2 = new String(s);
b2 = new String(b);
pending…
Prepend Empty String
var u, n = null,
    i = 87,
    s = 'tacos',
    b = true,
    u2, n2, i2, s2, b2;
u2 = '' + u;
n2 = '' + n;
i2 = '' + i;
s2 = '' + s;
b2 = '' + b;
pending…
Append Empty String
var u, n = null,
    i = 87,
    s = 'tacos',
    b = true,
    u2, n2, i2, s2, b2;
u2 = u + '';
n2 = n + '';
i2 = i + '';
s2 = s + '';
b2 = b + '';
pending…
Conditional toString
var u, n = null,
    i = 87,
    s = 'tacos',
    b = true,
    u2, n2, i2, s2, b2;
if (typeof u2 !== 'undefined') {
    //u2 = u.toString();
}
if (n2 !== null) {
    //n2 = n.toString();
}
i2 = i.toString();
s2 = s.toString();
b2 = b.toString();
pending…
toString, only when possible
var u, n = null,
    i = 87,
    s = 'tacos',
    b = true,
    u2, n2, i2, s2, b2;

i2 = i.toString();
s2 = s.toString();
b2 = b.toString();
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:

1 comment

NotWayne commented :

A mnemonic for you:

toString is better than

String is better than

new String is better than

appending.

Add a comment