Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【课外】8.15 性能问题 #12

Open
miniflycn opened this issue Aug 15, 2022 · 4 comments
Open

【课外】8.15 性能问题 #12

miniflycn opened this issue Aug 15, 2022 · 4 comments

Comments

@miniflycn
Copy link
Member

下面这段代码应当怎么优化性能更好:

for (let i = 0; i < items.length; i++) {
  document.getElementById("listGrid").innerHTML += "<tr><td>" + 
                                                   items[i].name + 
                                                   "</td></tr>";
}
@miniflycn
Copy link
Member Author

答案参考:https://calendar.perfplanet.com/2021/reducing-property-access/

如果自己心目中的答案比这个差可能要思考下是不是自己平时对运行性能不太关注。

@miniflycn miniflycn changed the title 8.15 性能问题 【课外】8.15 性能问题 Aug 15, 2022
@Nick-Dream
Copy link

心目中的答案就是这样的[狗头],避免循环操作dom引起的重绘、重排,把所有改变通过createDocumentFragment对象、JQ对象,html文本等形式缓存,最后一次性插入

@miniflycn
Copy link
Member Author

心目中的答案就是这样的[狗头],避免循环操作dom引起的重绘、重排,把所有改变通过createDocumentFragment对象、JQ对象,html文本等形式缓存,最后一次性插入

并不一定需要用createDocumentFragment,实际上跟把字符串拼装好再innerHTML性能差不多,差别只在于用createDocuemntFragement可以拿到被插入的对象,这样可以做些其他事情。

@Nick-Dream
Copy link

createDocuemntFragement的使用场景是把复制的dom对象进行组装,因为要保留它已绑定的事件

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants