javascript - 操作 jQuery 元素时 `array.join` 优于字符串连接的好处?

标签 javascript jquery arrays string performance

根据 this

The syntax for adding new elements to the page is easy, so it's tempting to forget that there's a huge performance cost for adding to the DOM repeatedly. If you're adding many elements to the same container, you'll want to concatenate all the HTML into a single string, and then append that string to the container instead of appending the elements one at a time. Use an array to gather all the pieces together, then join them into a single string for appending:

为什么我们必须使用数组?直接重复附加到字符串有什么问题?不是 string concatination suppose to be faster than array join?

最佳答案

存在性能成本是因为 DOM 元素上的 innerHTML 属性的行为不像简单的普通对象属性更新。每次设置 innerHTML 的值时,浏览器都会在幕后施展魔法。它必须经历启动 HTML 解析器并生成那些新标记的麻烦,替换之前存在的任何节点树。

反模式 element.innerHTML += string 是最糟糕的模式之一,因为它会导致浏览器首先将目标元素中的所有 HTML 字符串化,然后在末尾附加一个新字符串HTML,然后重新解析整个节点树,甚至在到达您添加的任何其他内容之前。

至少可以说,这是非常艰苦的工作。

如果您使用的是局部变量,则串联完全没问题。重点是,永远不要直接连接 innerHTML 属性。

var html = '<p>stuff</p>'
html += '<p>more stuff</p>'
html += '<p>even more stuff</p>'
html += '<p>extra stuff</p>'
element.innerHTML = html

但是,如果您需要立即和/或频繁更新 DOM,则更喜欢创建和附加新节点,而不是 innerHTML。例如,

var element = document.createElement('p')
element.textContent = 'Hello World'
document.body.appendChild(element)

关于javascript - 操作 jQuery 元素时 `array.join` 优于字符串连接的好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41009035/

相关文章:

javascript - 尝试在 Meteor 中添加包时出错

javascript - for循环不循环

javascript - JQUERY - ajax 调用后冒泡

javascript - jQuery.Form 不会提交

javascript - 如何将数组转换为分层数组

python - 将图像数据集存储到 4D 数组中然后显示每个图像会导致颜色失真

javascript - 具有嵌套关系的 TypeORM findOne

javascript - 制作姓名和年龄输入警报器

jQuery live() 删除 iPhone 触摸事件属性?

javascript - 如何在数组上使用 .filter() 仅删除 'NaN' 而不是字符串和数字?