简体   繁体   中英

Does the Javascript garbage collector delete unused key/value pairs?

I have a websocket system where I have an object called sessions , the key is the name of the session and the value is an array of the websockets while using the ws js library. I want to know if the garbage collector automatically deletes unused key/value pairs like old sessions or if I have to do it manually with the delete keyword.

No.

The garbage collection will clean up valies when there are no references left to them.

References can be object properties or variables.

A reference will only go away if the variable or property is overwritten with a new value, a property is expicitly delete d or if a variable falls out of scope (eg the function if it declared inside finished without returning a closure).


In your example:

sessions will be a reference to your object. It won't go away because you always have a reference to your collection of sessions.

Inside that object the properties pointing at the arrays won't go away because the object still exists.

If you want to delete one of the values of the object then you need to do so explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM