string 在 JavaScript 中连接字符串的最有效方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16696632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Most efficient way to concatenate strings in JavaScript?
提问by omega
In JavaScript, I have a loop that has many iterations, and in each iteration, I am creating a huge string with many +=
operators. Is there a more efficient way to create a string? I was thinking about creating a dynamic array where I keep adding strings to it and then do a join. Can anyone explain and give an example of the fastest way to do this?
在 JavaScript 中,我有一个包含多次迭代的循环,并且在每次迭代中,我都会创建一个包含许多+=
运算符的巨大字符串。有没有更有效的方法来创建字符串?我正在考虑创建一个动态数组,在其中不断向其中添加字符串,然后进行连接。任何人都可以解释并举例说明最快的方法吗?
采纳答案by Jakub Hampl
Seems based on benchmarks at JSPerfthat using +=
is the fastest method, though not necessarily in every browser.
似乎基于JSPerf 的基准测试,使用+=
是最快的方法,尽管不一定在每个浏览器中。
For building strings in the DOM, it seems to be betterto concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.
对于在 DOM 中构建字符串,似乎最好先连接字符串然后添加到 DOM,而不是迭代地将其添加到 dom。不过,您应该对自己的案例进行基准测试。
(Thanks @zAlbee for correction)
(感谢@zAlbee 的更正)
回答by zAlbee
I have no comment on the concatenation itself, but I'd like to point out that @Jakub Hampl's suggestion:
我对串联本身没有评论,但我想指出@Jakub Hampl 的建议:
For building strings in the DOM, in some cases it might be better to iteratively add to the DOM, rather then add a huge string at once.
对于在 DOM 中构建字符串,在某些情况下,迭代添加到 DOM 可能更好,而不是一次添加一个巨大的字符串。
is wrong, because it's based on a flawed test. That test never actually appends into the DOM.
是错误的,因为它基于有缺陷的测试。该测试实际上从未附加到 DOM 中。
This fixed testshows that creating the string all at once before rendering it is much, MUCH faster. It's not even a contest.
这个固定的测试表明,在渲染之前一次性创建所有字符串要快得多。这甚至不是比赛。
(Sorry this is a separate answer, but I don't have enough rep to comment on answers yet.)
(对不起,这是一个单独的答案,但我还没有足够的代表来评论答案。)
回答by Volodymyr Usarskyy
Three years past since this question was answered but I will provide my answer anyway :)
自从回答这个问题三年过去了,但无论如何我都会提供我的答案:)
Actually, accepted answer is not fully correct. Jakub's test uses hardcoded string which allows JS engine to optimize code execution (Google's V8 is really good in this stuff!). But as soon as you use completely random strings (here is JSPerf) then string concatenation will be on a second place.
实际上,接受的答案并不完全正确。Jakub 的测试使用了硬编码字符串,它允许 JS 引擎优化代码执行(谷歌的 V8 在这方面真的很棒!)。但是一旦您使用完全随机的字符串(这里是 JSPerf),那么字符串连接将排在第二位。
回答by Madbreaks
You can also do string concat with template literals. I updated the other posters' JSPerf teststo include it.
您还可以使用模板文字进行字符串连接。我更新了其他海报的JSPerf 测试以包含它。
for (var res = '', i = 0; i < data.length; i++) {
res = `${res}${data[i]}`;
}