I am using D3.js and often find myself dynamically building transform
attributes (or d
attributes on path
elements). Both of these often require multiple comma-separated numbers.
Sometimes I build my strings by concatenating an array to string:
var x = 0,
y = 1,
path = 'M0,0 L' + [x, y];
And sometimes I build my strings by manually adding the comma:
var x = 0,
y = 1,
path = 'M0,0 L' + x + ',' + y;
I've decided that I should try to stick to one method or the other, and am wondering which approach is the better one to take.
Here are a few things I've considered:
join()
is slower than manually concatenating the commas, but is that what the browser does when it concatenates an array to a string?Is there one way that is definitively better than the other? Or am I just being nitpicky?
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
You can use the square bracket operator [] to concatenate or append arrays. For example, [A,B] and [A B] concatenates arrays A and B horizontally, and [A; B] concatenates them vertically.
In order to convert an array into a string in Javascript, we simply apply the toString() method on the given array, and we get a stringified version of our array. Internally javascript first converts each element into string and then concretes them to return the final string.
When JavaScript coerces an array to a string, it actually call: .join(',')
on the array. So you're actually going to be getting better performance with .join(',')
manually as opposed to leaving it up to the interpreter to notice you're coercing the array. So: x + ',' + y
is the fastest, [x, y].join(',')
is the best practice(since it makes it easier to modify the behavior), and [x, y]
is a tiny bit slower than manually calling .join
and can be unreadable at times, but it's more convenient.
the short answer: use array.join.
the long answer:
First off, concatenation isn't faster than using array.join(), it's slower. this is because each time you concatenate you destroy two strings and create a new one.
take the following code:
<script>
function concat(){
var txt = '';
for (var i = 0; i < 1000000; i++){
txt =+ i + ',';
}
}
function arr(ar){
var txt = 'asdf' + ar;
}
ar = [];
for (var i = 0; i < 1000000; i++) {
ar.push(i);
}
concat();
arr(ar);
alert('done!');
</script>
and paste it into an html file. Then profile it. On my machine (core i7EE, 16GB RAM, SSD disks, IE9), arr() takes 0ms and concat() takes 12ms. Keep in mind this is over a million iterations (this same test would be quite different on IE6, concat() would take seconds).
Second, concatenation will take the same as array.join when having only two values. So for your example, from a performance perspective, they're both equivalent. if you take the above code and change the 1000000 to 4, both concat and arr take 0ms to execute. this means the difference for your particular flow is either inexistent or so negligible it doesn't show up in a profile.
Third, modern browsers optimize string concatenation using array.join() anyways, so the discussion is probably moot from a performance point of view.
That leaves us with style. Personally, I wouldn't use the first form because I don't like manually concatenating strings (when you've got 2 vars it's rather straightforward, but what if you have 10 vars? that'll make a really long line of code. And what if you receive an array with n values, in comes a for loop). I wouldn't use the second form either because, as pointed out in another answer, the value is coerced to a string, and that means some implicit transformation is going on. The problem here is the implicit part. I know now arrays are joined with a comma when coerced, but what happens if the spec changes, or some genius decides to change the toString implementation of Array.prototype in your codebase? just for fun run this in jsfiddle:
Array.prototype.toString = function() {
return 'not the expected result!';
}
alert([1, 2]);
Can you guess what the answer will be? (the above code will execute the same kind of conversion for the array as your code. coercion via the toString() method)
if you use array.join(','); you'll be futureproofing your code by stating that 1) your array will be joined regardless of the toString implementation and 2) it will be joined with a comma.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With