.append VS .html VS .innerHTML表现 [英] .append VS .html VS .innerHTML performance

查看:95
本文介绍了.append VS .html VS .innerHTML表现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此网站在3种不同方法之间运行测试,似乎 .html 最快,其次是 .append 。然后是 .innerHTML 。有人可以向我解释原因吗?

This site's run a test between the 3 different methods and it seems .html is the fastest, followed by .append. followed by .innerHTML. Can someone explain to me the reasons why?

这是在三种方法中进行比较的网站。

Here's the site which does the comparison among the three methods.

我读过这个这个问题这是相关的,但我真的不理解给定的答案,而且这个问题并没有真正详细阐述 .innerHtml

I have read this this SO question which is related but I don't really understand the given answer, and the question didn't really elaborate much regarding .innerHtml.

我不明白以下部分:


创建一个临时元素,我们称之为x。 x的innerHTML设置为您传递的HTML字符串。然后jQuery将每个生成的节点(即x的childNodes)转移到新创建的文档片段,然后它将被缓存以供下次使用。然后它将片段的childNodes作为新的DOM集合返回。
请注意,它实际上要复杂得多,因为jQuery会进行一系列跨浏览器检查和各种其他优化。例如。如果您只将< div>< / div> 传递给jQuery(),jQuery将采用快捷方式,只需执行document.createElement('div')。

A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection. Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').

有人可以简化这个吗?

推荐答案

那个基准毫无价值。 innerHTML 总是比DOM操作更快。

That benchmark is worthless. innerHTML is always faster than DOM manipulation.

jQuery 似乎更快,因为它准备了首先是所有HTML的字符串,而其他的每次迭代都会执行一次操作。另请注意,jQuery.html()只要可以使用 innerHTML

jQuery seems faster because it prepares a string with all the HTML first while the others do one operation each iteration. Also note that jQuery.html() uses innerHTML whenever it can.

var html = '';
for (var i = 0; i < len; i++) {
  html += '<div>Test ' + i + '</div>';
}

$('#list').html(html);



来自基准的innerHTML



innerHTML from benchmark

var list = document.getElementById('list');
for (var i = 0; i < len; i++) {
  list.innerHTML = list.innerHTML + '<div>Test ' + i + '</div>';
}






对<$的测试c $ c> innerHTML 如果编写如下:会快得多:


The test for innerHTML would be a lot faster if it was written like:

var list = document.getElementById('list');
var html = '';

for (var i = 0; i < len; i++) {
    html += '<div>Test ' + i + '</div>';
}

list.innerHTML = html;

http://jsben.ch/#/yDvKH

这篇关于.append VS .html VS .innerHTML表现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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