在JavaScript中连接字符串的最有效方法? [英] Most efficient way to concatenate strings in JavaScript?

查看:163
本文介绍了在JavaScript中连接字符串的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我有一个循环,有许多迭代,并且在每次迭代中,我创建了一个包含许多 + = 运算符的大字符串。有没有更有效的方法来创建一个字符串?我正在考虑创建一个动态数组,我不断添加字符串,然后进行连接。任何人都可以解释并举例说明最快的方法吗?

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?

推荐答案

似乎基于 + = 的http://jsperf.com/join-concat/2rel =noreferrer> JSPerf 是最快的方法,但不一定在每个浏览器中。

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

为了在DOM中构建字符串,它似乎更好首先连接字符串然后添加到DOM,而不是迭代地将它添加到dom。你应该对你自己的情况进行基准测试。

For building strings in the DOM, it seems to be better to 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.

(感谢@zAlbee进行更正)

(Thanks @zAlbee for correction)

这篇关于在JavaScript中连接字符串的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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