Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to convert a number to a string in JavaScript?

What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?

Some examples:

  1. String(n)

  2. n.toString()

  3. ""+n

  4. n+""

like image 503
Pacerier Avatar asked Apr 23 '11 16:04

Pacerier


People also ask

What is the fastest way to convert number to string in JavaScript?

Fastest based on the JSPerf test above: str = num. toString();

Which method converts a given value into a string in JavaScript?

The String() method converts a value to a string.


2 Answers

like this:

var foo = 45; var bar = '' + foo; 

Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()

See Performance tests here (not by me, but found when I went to write my own): http://jsben.ch/#/ghQYR

Fastest based on the JSPerf test above: str = num.toString();

It should be noted that the difference in speed is not overly significant when you consider that it can do the conversion any way 1 Million times in 0.1 seconds.

Update: The speed seems to differ greatly by browser. In Chrome num + '' seems to be fastest based on this test http://jsben.ch/#/ghQYR

Update 2: Again based on my test above it should be noted that Firefox 20.0.1 executes the .toString() about 100 times slower than the '' + num sample.

like image 110
scunliffe Avatar answered Oct 19 '22 12:10

scunliffe


In my opinion n.toString() takes the prize for its clarity, and I don't think it carries any extra overhead.

like image 35
CarlosZ Avatar answered Oct 19 '22 13:10

CarlosZ