JavaScript:字符串连接性能慢?Array.join('')? [英] JavaScript: String Concatenation slow performance? Array.join('')?

查看:73
本文介绍了JavaScript:字符串连接性能慢?Array.join('')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过如果我有一个 for 循环,我不应该使用字符串连接,因为它很慢.如:

I've read that if I have a for loop, I should not use string concation because it's slow. Such as:

for (i=0;i<10000000;i++) {
    str += 'a';
}

相反,我应该使用 Array.join(),因为它要快得多:

And instead, I should use Array.join(), since it's much faster:

var tmp = [];
for (i=0;i<10000000;i++) {
    tmp.push('a');
}
var str = tmp.join('');

但是,我也读到字符串串联只是 Internet Explorer 的一个问题,并且使用 Webkit 的 Safari/Chrome 等浏览器实际上比 Array.join()Array.join()代码>.

However, I have also read that string concatention is ONLY a problem for Internet Explorer and that browsers such as Safari/Chrome, which use Webkit, actually perform FASTER is using string concatention than Array.join().

我试图在所有主要的字符串连接浏览器与 Array.join() 之间进行性能比较,但一直没有找到.

I've attempting to find a performance comparison between all major browser of string concatenation vs Array.join() and haven't been able to find one.

因此,什么是更快、更高效的 JavaScript 代码?使用字符串连接还是 Array.join()?

As such, what is faster and more efficient JavaScript code? Using string concatenation or Array.join()?

推荐答案

似乎 Array.join() 在大多数情况下跨浏览器更快.

It appears Array.join() for the most part across browsers is faster.

FF3        array.join is ~2x faster
Safari 3   array.join ~1.5x faster
Opera 9    += ~3x faster
ie6     array.join ~6x faster
ie7     array.join ~4x faster

下一代浏览器

FF3.1      += array.join equal in speed
Chrome     +=  ~1.25x faster
IE8     array.join ~1.6x faster
Webkit     array.join ~2x faster

测试结果在这里:http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

这篇关于JavaScript:字符串连接性能慢?Array.join('')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆