Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference between []+[] and [].join(',')+[].join(',')

Tags:

javascript

Just while fiddling through arrays i found this.

why there is significant difference between the following three statements:

[1,2]+[3,4];

[1,2].toString()+[3,4].toString();

[1,2].join(',')+[3,4].join(',');

enter image description here And if [1,2]+[1,2] performs the same as converting to string and then joining the two strings, then shouldnt be performance of them be somewhat similar

This question is inspired from this answer

like image 611
Naeem Shaikh Avatar asked May 12 '26 13:05

Naeem Shaikh


1 Answers

It probably has something to do with implicit and explicit coercion.

For [1,2]+[3,4], the interpreter has to figure out on it's own that string is the desired output.

For both [1,2].toString()+[3,4].toString(); and [1,2].join(',')+[3,4].join(',');, you're already telling the interpreter it's working with strings.

The difference between the last 2 lines is pretty much negligible.

In the end, even if you're doing this a million times, you're not really going to notice a difference.

like image 192
Cerbrus Avatar answered May 15 '26 02:05

Cerbrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!