What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
Some examples:
String(n)
n.toString()
""+n
n+""
What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
Some examples:
String(n)
n.toString()
""+n
n+""
It seems similar results when using node.js. I ran this script:
and got the following results:
Similar times each time I ran it.
I'm going to re-edit this with more data when I have time to, for right now this is fine...
Test in nodejs v8.11.2: 2018/06/06
output
If I had to take everything into consideration, I will suggest following
IMHO, its the fastest way to convert to string. Correct me if I am wrong.
We can also use the String constructor. According to this benchmark it's the fastest way to convert a Number to String in Firefox 58 even though it's slower than
" + num
in the popular browser Google Chrome.I used https://jsperf.com to create a test case for the following cases:
https://jsperf.com/number-string-conversion-speed-comparison
As of 24th of July, 2018 the results say that
number + ''
is the fastest in Chrome, in Firefox that ties with template string literals.Both
String(number)
, andnumber.toString()
are around 95% slower than the fastest option.I like the first two since they're easier to read. I tend to use
String(n)
but it is just a matter of style than anything else.That is unless you have a line as
which is very self explanatory