JavaScript字符串连接的性能问题
在Professional JavaScript for Web Developers(第二版)一书中,看到一个关于字符串操作的例子,原文大意如下:
第2到6步在每次字符串拼接的时候都发生,使这个操作很费时。当该操作进行成千上万次时,性能上会有问题。解决的办法是使用Array来存储string并使用join()方法来创建最后的string.可用以下代码替代:
最后,作者说,实际的情况是,使用“+”操作符,要比使用数组的方法节省100-200%的性能。
================================================================================
上面都是在这本书中写到的,我实际测试了下,在不同浏览器下有差异。
IE 9:
Concatenation with plus: 3036milliseconds
Concatenation with StringBuffer: 1210 milliseconds
Firefox 11.0
Concatenation with plus: 269milliseconds
Concatenation with StringBuffer: 3245 milliseconds
Chrome 18.0.1025.152 m
Concatenation with plus: 3081milliseconds
Concatenation with StringBuffer: 3455 milliseconds
可以看到,在IE9下,使用数组的方式效率反而更高,只有使用“+”操作符的40%,在FF下,使用“+”操作符交通大大优于数组方式,在Chrome下,两种方式差不多。