Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是[x,y,z].join(';';)真的比x+;y+;z代表字符串?_Javascript_Performance_Concatenation - Fatal编程技术网

Javascript 是[x,y,z].join(';';)真的比x+;y+;z代表字符串?

Javascript 是[x,y,z].join(';';)真的比x+;y+;z代表字符串?,javascript,performance,concatenation,Javascript,Performance,Concatenation,对于字符串,join(“”)真的比x+y+z快吗 在join()更快的印象下,我开始通过代码使用它,而不是+,然后在Google Analytics代码中遇到以下行: ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 假设谷歌的程序员是最有知识的,这让我感到奇怪。当然,该行在每次页面加载时只运行一次,可以说任

对于字符串,join(“”)真的比
x+y+z
快吗

在join()更快的印象下,我开始通过代码使用它,而不是+,然后在Google Analytics代码中遇到以下行:

    ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
假设谷歌的程序员是最有知识的,这让我感到奇怪。当然,该行在每次页面加载时只运行一次,可以说任何速度差都可以忽略不计。但是仍然?

用于连接字符串的数组
.join()
方法(-trick)的根源可以追溯到网站在Internet Explorer上运行时。对于IE6+7来说,它比
.join()
更为正确。由于IE中的字符串操作行为非常糟糕,因此它比使用
+
操作符快得多


对于其他浏览器,性能差异并没有那么大,因此建议使用
.join()
(同样,在当时)。现在,大多数引擎都会大量优化字符串操作,除非您认为您的任何代码都在IE6+7中大量运行,否则您应该使用Firefox 6.0.2中的Firebug控制台使用以下代码:

b = new Date().getTime(); for (var i = 0; i < 10000; i++) {a = "sfhfdshdshsdh" + "sfhsfdhsfhdsfh" + "shsfdsdgsdgsgsdfgdfsgsfdghsdfhsdh";} c = new Date().getTime(); d = c - b;
b=newdate().getTime();对于(变量i=0;i<10000;i++){a=“sfhfdshdshsdh”+“sfhsfdhsfhdsfh”+“shsfdsdgdgsgdfsgsfdghsdfhsh”;}c=new Date().getTime();d=c-b;

b=newdate().getTime();对于(变量i=0;i<10000;i++){a=[“sfhfdshdshsdh”,“sfhsfdhsfhdsfh”,“shsfdsdgdgsgsdfgdfsgsfdghsdfhsh”]。join();}c=new Date().getTime();d=c-b;

我的平均值是“+”的40分,而“join”的50分,所以join似乎较慢。这很可能是因为需要为join创建一个数组。在不同的浏览器中,使用不同的解释器也可能会有所不同。

下面是我在google chrome上运行的一个示例

试试其他的兄弟

在chrome中,我的
+
总是更快


函数的速度由JavaScript实现决定,JavaScript实现因浏览器而异。用于测试-这也是
[x,y]。加入(“”)
。我相信节省的是更多的参数(因为您使用
+
对每个append执行一个调用,而join只是一个函数调用。)+Bakudan发现了一个测试,该测试应该可以提供一些启示:
b = new Date().getTime(); for (var i = 0; i < 10000; i++) {a = ["sfhfdshdshsdh","sfhsfdhsfhdsfh","shsfdsdgsdgsgsdfgdfsgsfdghsdfhsdh"].join();} c = new Date().getTime(); d = c - b;