I have this code:
var boo = 123123;
I want to convert that number to string and conact string is faster than native JavaScript .toString():
Faster:
var foo = boo + "";
Slower:
var foo = boo.toString();
jsPerf: http://jsperf.com/concat-string-vs-tostring
Why .toString() is slower than concating empty character? And finally I want to know is that a correct approach to use + "" technique instead of .toString()?
Results will vary depends on javascript engine used. On chrome one I’m getting the same results as Afshin.
So why actually one is slower than another? It’s because on
toStringthere will be one more call to C functions inside V8. You can try next to see that by yourself:script1script, press enter.Repeat the same with
script2script 1:
var boo = 123123; var foo = boo + "";script 2:
var boo = 123123; var foo = boo.toString();In my case first will result in next stacktrace:
while second one:
I think it’s more has to do with engine internals than official js spec and probably could be optimized to use the same code path.