3

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

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88

1 Answers1

4

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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147