15

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:

  • I know that calling join() is slower than manually concatenating the commas, but is that what the browser does when it concatenates an array to a string?
  • The second format will work in any browser. Are there any browsers that don't support the first format?
  • The first format uses less characters (keeping file sizes low is always a plus).
  • Personally, I believe the first format is more readable.

Is there one way that is definitively better than the other? Or am I just being nitpicky?

1
  • 1
    You're just being nitpicky :-) I'd choose the one that's more readable (and in my opinion, that's the second one). Commented Sep 27, 2013 at 1:47

2 Answers 2

23

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was surprised to find how much faster x + ',' + y actually is. In my case, it was about 4 times faster than [x, y]. (jsfiddle.net/8VqEP)
5

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.

4 Comments

I agree with your point on implicit transformation - that's something I didn't think of. I disagree, however, on your performance test. I'm building my String in a single line of code, not iteratively in a loop. A better test case would be something like this (see this fiddle jsfiddle.net/8VqEP). You'll see here that performance ratings in TenorB's answer are accurate.
the point of the test was to show that any difference is negligible (12 ms is almost nothing) and to illustrate how slower string concatenation is when working with big strings (1000000 iterations makes for a long string). Your fiddle compares joining an array vs concatenating a really small string. After modifying it a bit (you were building the array in each iteration, that can pollute the test since we're profiling concatenation, not object creation), I get back to my second point. my times were 502, 2 and 91, that's approximately 0.000502ms per iteration for the slowest test. negligible.
that brings us back to the intent of my post. since performance is negligible, you should use array.join for the reasons stated above
it seems jsfiddle adds a bit of overhead to the profiling. If you run the code natively (i.e. from an html file loaded into a browser), results are 266, 238, 180; making array.join() the fastest (these are just my results, they could be different in your environment, but they prove my point: performance is negligible).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.