开发者

String join in JScript?

How do I join a bunch of strings with a separator in JScript?

(I'm loo开发者_如何学JAVAking for a solution with linear running time.)


Like the join() method? =D

var elements = ["1", "2", "3"];
var joinedString = elements.join(',');


Somthing like this:

['a', 'b', 'c'].join(',');

However, for small number of strings, + operator will also do fine (and may do better depending on circumstances). Here's a nice article comparing the 2 approaches.

And a jsperf page for the skeptics.


You can use join on an array.

var strArray = [
    "test1",
    "test2",
    "test3"
];

var output = strArray.join(", ");

Here's a jsperf test of a couple different methods here: http://jsperf.com/joining-strings. Join is definitely the fastest of the ways I tried, by at least 3x (in Chrome).

You'll have to try out the jsperf yourself and/or change it to model exactly what you care about. To my surprise, Firefox 6 and Safari 5 are faster just adding a bunch of strings together than using .join().

You said you're looking for a solution with linear running time. I presume that means that when you double the number of strings, the performance is no worse than double. That means you'd have to test a bunch of different cases and see which technique was closest to linear performance. The first jsperf was concatenating 9 strings with separators between them. So, I wrote a second jsperf that was concatenating 18 strings with separators between them. None of the techniques were quite linear in Chrome. Oddly enough, the for loop += method which is the slowest overall was closest to linear. So, I think you have to decide whether you want fast or linear. The slowest method I tried is the closest to linear, but it's still slow. If you're concatenating really large numbers of strings, then you'd have to test that specific case to see which one wins for either linearity or overall performance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜