blob: 29c92782efa0c58ab9c2fd6a44d84246d20bc4ee (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
---
title: DOM allocation example
slug: Tools/Memory/DOM_allocation_example
tags:
- 内存
- 开发者工具
translation_of: Tools/Memory/DOM_allocation_example
---
<div>{{ToolsSidebar}}</div>
<p>这篇文章描述了一个简单的 Web 页面,它被用于阐述内存工具的一些特性。</p>
<p>你可以在这个网页中试试:<a href="https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html">https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html</a>。</p>
<p>它仅仅包含了一个创建大量 DOM 节点的脚本:</p>
<pre class="brush: js">var toolbarButtonCount = 20;
var toolbarCount = 200;
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function createToolbarButton() {
var toolbarButton = document.createElement("span");
toolbarButton.classList.add("toolbarbutton");
// stop Spidermonkey from sharing instances
toolbarButton[getRandomInt(0,5000)] = "foo";
return toolbarButton;
}
function createToolbar() {
var toolbar = document.createElement("div");
// stop Spidermonkey from sharing instances
toolbar[getRandomInt(0,5000)] = "foo";
for (var i = 0; i < toolbarButtonCount; i++) {
var toolbarButton = createToolbarButton();
toolbar.appendChild(toolbarButton);
}
return toolbar;
}
function createToolbars() {
var container = document.getElementById("container");
for (var i = 0; i < toolbarCount; i++) {
var toolbar = createToolbar();
container.appendChild(toolbar);
}
}
createToolbars();
</pre>
<p>一段表示代码工作流程的伪代码:</p>
<pre>createToolbars()
-> createToolbar() // 调用 200 次, 每次创建一个 DIV 元素
-> createToolbarButton() // 每次调用 createToolbar() 时,调用 20 次,每次创建一个 SPAN 元素</pre>
<p>它总共创建了 200 个 <code><a href="/en-US/docs/Web/API/HTMLDivElement">HTMLDivElement</a></code> 对象和 4000 个 <code><a href="/en-US/docs/Web/API/HTMLSpanElement">HTMLSpanElement</a></code> 对象。</p>
|