天天看点

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

I use the following simple 

JavaScript

 code to illustrate:

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

The Snapshot1 is generated.

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

And switch to Profiles tab again to make the second snapshot:

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

We can find out from column “New” that 100 div nodes are created as we expect.

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

Since these nodes are not appended to document node so they are invisible to end user, so displayed as “Detached DOM”. The JerryTestArray still holds the reference to each div node so Garbage collector will not touch these nodes.

In order to make Garbage collector recycle the memory occupied by these nodes, just assign another value to JerryTestArray in console:

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

Once done, make the third snapshot and compare it with the second. Now we can find that the re-assignment to JerryTestArray will trigger the destruction of those 100 div nodes by Garbage collector:

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理
使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

Now stop the profile. The profile is displayed as below. The highlighted vertical blue line indicates the timeslot when the 97 Span elements are created. Note that the number of Span elements displayed here is not 98 but 97 since Chrome development tool displays the final status of objects after “stop profile” button is clicked ( the reference to 30th Span element is replaced by String, so it is recycled by GC ).

使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理
使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理
使用Chrome开发者工具分析JavaScript garbage collector(垃圾回收器)的实现原理

For more tips How I use Chrome development tool in my daily work, please refer to this blog Chrome Development Tool tips used in my daily work