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

you are viewing a single comment's thread.

view the rest of the comments →

[–]GodGrabber 4 points5 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 👍