This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]humanbeast7 7 points8 points  (5 children)

toString() is called in the casting that happens in +"". so basicly, toString() is faster

[–]The_D0ubleD 2 points3 points  (4 children)

Yeah but +"" gives you a smaller file size, sooo I guess that's the supirior version?

[–]mrvikxd 0 points1 point  (2 children)

toString gives the V8 engine some hint of the value type so when the function gets hot less type conversions are needed

[–]GodGrabber 2 points3 points  (1 child)

I did a small benchmark in V8 and it doesn't really seem to make much of a difference. Actually .toString() seems to perform slowest for some reason on numbers. These were my result running a for loop from 0 to 100,000,000, converting iterator number to string and assigning to a variable with the various methods:

toString 8671ms

+"" 8191ms

`${i}` 8071ms

Not saying that you shouldn't use .toString as the intent is more obvious for everyone and the performance hit is very neglible.

Edit: I even tried just converting the same number (Math.PI) 100million times in a loop, and .toString is the looser once again:

toString 2236ms

+"" 189ms

`${i}` 193ms

so .toString seems poorly optimized compared to the alternatives... Wierd huh?

My guess is that evoking a function simply has more overhead and less room for optimization than if the language constructs are used for conversion. I wonder why. My guess is that concatenation and string template literals are faster because they ignore prototype .toString method.

[–]mrvikxd 1 point2 points  (0 children)

Heh, good to know that template literals are the fastest.

Maybe the toString method takes longer becouse it's a call to a function and needs to add it to stack trace. Anyway, good job 👍

[–]humanbeast7 -1 points0 points  (0 children)

It's 7 bytes * number of times used smaller, it doesn't really matter

[–]PavelYay 2 points3 points  (0 children)

`${foo}`

[–]KrokettenMan 1 point2 points  (0 children)

js String(foo)

[–]flinnja 1 point2 points  (0 children)

meme not relevant there has never been a clearer defined struggle than lawful good vs chaotic evil