Reputation: 34929
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()
?
Upvotes: 5
Views: 1239
Reputation: 7038
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 toString
there will be one more call to C functions inside V8. You can try next to see that by yourself:
script1
script, press enter. Repeat the same with script2
script 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:
InjectedScript.evaluate
InjectedScript._evaluateAndWrap
while second one:
InjectedScript.evaluate
InjectedScript._evaluateAndWrap
InjectedScript._evaluateOn
evaluate
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.
Upvotes: 5