如何检测在 JavaScript 中触发垃圾收集的内存分配?

在寻找 JavaScript 库(铆钉)中的性能问题时,我发现垃圾收集在一次运行中发生了 3 到 4 次,占用了大约 15% 的执行时间(使用 Chrome DevTools JS Profile).

While looking for performance issues in a JavaScript library (rivets), i found that garbage collection occurs three to four times in a run, taking ~15% of execution time (using Chrome DevTools JS Profile).

由于垃圾回收的原因,至少有 30 个地方创建了临时函数/对象作为潜在候选对象.

There are at least 30 places where temporary functions / objects are created being potential candidates for the reason of the garbage collection.

我想知道是否有办法找到负责分配被垃圾回收的内存的函数,这样我就可以专注于我的性能调整.

I'd like to know if there's a way to find what functions are responsible for the allocation of the memory being garbage collected, so i can focus my performance tuning.

我记录了堆分配时间线,但它没有区分被垃圾收集的内存并且仍然持有引用(没有像 DevTools 中指出的灰色条 doc)

I recorded Heap Allocation TimeLine but it does not differentiate memory that was garbage collected and that still holds a reference (there's no gray bar as pointed in DevTools doc)

还没有运气记录堆分配配置文件.

Also recorded Heap Allocation Profile without luck.

推荐答案

DevToolsProfiles 选项卡中选择 Record Heap Allocation.包装 javascript 应在对 setTimeout() 的调用中进行评估,持续时间设置为足够的时间,以便在函数传递给 之前单击 Start>setTimeout 被调用;例如

At Profiles tab at DevTools select Record Heap Allocation. Wrap javascript which should be evaluated within a call to setTimeout() with a duration set to enough time to click Start before function passed to setTimeout is called; for example

<!DOCTYPE html>
<html>
<head>
  <script>
    t = 5;
    setTimeout(function() {
      (function test1() {
        var a = 123;
        function abc() {
          return a
        }
        abc();
      }());
    }, 10000)
  </script>
</head>
<body></body>
</html>

setTimeout 被称为蓝条时,可能会在时间轴上出现一个灰条.单击 Ctr+E 停止记录堆配置文件.

When setTimeout is called a blue bar, possibly followed by a gray bar should appear at timeline. Click Ctr+E to stop recording heap profile.

在时间线图中选择蓝色或灰色条.在默认选项为 Summary 的下拉菜单中选择 Containment.选择

Select blue or gray bar at timeline graph. Select Containment at dropdown menu where default option is Summary. Select

[1] :: (GC roots) @n

其中 n 是一个数字.

通过单击[1] :: (GC 根) 左侧的三角形来展开选择.选择[1] :: (GC root)的一个元素,查看显示的DistanceShallow SizeRetained Size 用于选择的列.

Expand the selection by clicking triangle to left of [1] :: (GC roots). Select an element of [1] :: (GC roots), review the displayed Distance, Shallow Size, and Retained Size columns for the selection.

要查看特定功能,请滚动到

To check specific functions, scroll to

[2] :: (External strings) @n

到应该列出全局变量和函数调用的位置;例如,"t""setTimeout" 来自 javascrip.检查相应的 DistanceShallow SizeRetained Size 列以进行选择.

to where global variables and function calls should be listed; i.e.g., "t" and "setTimeout" from above javascrip. Check corresponding Distance, Shallow Size, and Retained Size columns for the selection.

相关文章