JScript 中的字符串连接?
如何在 JScript 中使用分隔符连接一堆字符串?
(我正在寻找具有线性运行时间的解决方案。)
How do I join a bunch of strings with a separator in JScript?
(I'm looking for a solution with linear running time.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
喜欢
join()
方法吗? =DLike the
join()
method? =D事情是这样的:
但是,对于少量字符串,
+
运算符也可以很好地工作(并且根据情况可能会做得更好)。这是一篇很好的文章,比较了这两种方法。还有一个针对怀疑者的 jsperf 页面。
Somthing like this:
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.
您可以在数组上使用 join。
以下是对几种不同方法的 jsperf 测试:http://jsperf.com/joining-strings。 Join 绝对是我尝试过的最快的方法,至少快了 3 倍(在 Chrome 中)。
您必须亲自尝试 jsperf 和/或更改它以准确模拟您关心的内容。令我惊讶的是,Firefox 6 和 Safari 5 将一堆字符串添加在一起比使用
.join()
更快。您说您正在寻找具有
线性
运行时间的解决方案。我认为这意味着当您将字符串数量加倍时,性能不会比加倍差。这意味着您必须测试一堆不同的情况,看看哪种技术最接近线性性能。 第一个 jsperf 用分隔符连接 9 个字符串。因此,我编写了一个第二个jsperf,它将 18 个字符串连接在一起,并在它们之间使用分隔符。在 Chrome 中,这些技术都不是完全线性的。奇怪的是,整体最慢的 for 循环 += 方法最接近线性。所以,我认为你必须决定你想要快速还是线性。我尝试过的最慢的方法是最接近线性的,但它仍然很慢。如果您要连接大量字符串,那么您必须测试特定情况,看看哪一个在线性度或整体性能方面胜出。You can use join on an array.
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.