Is this a Memory Leak?

Writing this on mobile, apologies for any formatting or autocorrect

Scenario:

A script creates a few BindableEvents, leaves them parented to nil, and creates a few connections on them.

Then, the script is set to Disabled, killing all its threads and refs.

There are therefore no more references to these Instances, and they’re in nil so no other script can access them afaik.

Will these be :Destroy()ed and GCed automatically, or did I just create Instances that will eat memory forever?

3 Likes

You can check memory in the developer console by pressing f9 in-game. This is a good way on finding any memory leaks

2 Likes

They will be collected as they are no longer referenced anywhere.

Imagine the events as tables that contain those binded functions. The functions are referenced in the table, but the table isn’t referenced anywhere. The table will get collected and the functions will no longer referenced. The functions are then collected in the second cycle.

The above is overly simplified and not exactly how a collection cycle works, but it is good enough as an example.

I’m out on a vacation with no PC but this question hit me and I can’t sleep without knowing :sob::sweat_smile:

2 Likes

I could have sworn I’ve seen posts saying that you have to :Destroy() to ensure GC instead of just parenting to nil and removing refs?

Edit:
I’m wrong. That was in regard to the connections on the Instance. :Remove() doesn’t handle connections on the Instance, :Destroy() does.

1 Like

Because :Destroy() marks the instance for collection by locking the parent property. You can actually call destroy on an instance and still print its name before a collection cycle takes place.

If an instance is only referenced in a single script (in your case i guess they are used as custom events), it doesn’t exactly matter much and is more of a failsafe in case you modify the code. Especially because the instances and functions arent used outside the script.

1 Like

If the connections hold a reference to the BindableEvents, it’s possible that there is a memory leak, they will not be Destroyed just because you disabled the script. As boatbomber linked to, and contrary to what nooneisback says, Destroy does not “mark the Instance for collection.” The important difference in this case between setting the Parent to nil, Remove, and Destroy is the fact that Destroy does not defer the disconnection of all connected event connections to the GC metamethod but directly disconnects them. Disconnecting the event connections will ensure the bug that was mentioned (by stravant) a while ago does not apply. Otherwise, references to a BindableEvent in the BindableEvent’s event connections will prevent the BindableEvent from being GC’d.

Edit: this is the bug I’m referring to: PSA: Connections can memory leak Instances!

1 Like