Can I trigger JavaScript's garbage collection?

后端 未结 9 2035
不知归路
不知归路 2021-01-31 07:17

I want to trigger JavaScript garbage collection. Is it possible? Why would I want to, or not want to, do this?

9条回答
  •  野的像风
    2021-01-31 07:35

    Came across this question and decided to share with my recent findings. I've looked to see a proper handling of a WeakMap in Chrome and it's actually looks okay:

    1) var wm = new WeakMap()

    2) var d = document.createElement('div')

    3) wm.set(d, {})

    at this stage weak map holds the entry cause d is still referencing the element

    4) d = null

    at this stage nothing references the element and it's weakly referenced object, and indeed after a couple of minutes entry disappeared and garbage collected.

    when did the same but appended the element to the DOM, it was not reclaimed, which is correct, removed from the DOM and still waiting for it to be collected :)

提交回复
热议问题