A question about disconnecting connections to prevent memory leaks

I’m not sure how memory leaks happen and how to prevent them properly.

I already tend to disconnect my connections that are within for loops using janitor or just a :Disconnect.

But when I have a connection for every player on the server will it cause memory leaks because once that player leaves that connection is never disconnected?

for _, player in pairs(players:GetPlayers()) do
	player.leaderstats.Shapes.Changed:Connect(function()
		shapesLeaderboard:Append(player.UserId, player.leaderstats.Shapes.Value)
	end)
end

like are memory leaks client only or do i need to worry about them on the server too?

Memory leaks are basically events that aren’t used anymore. Basically outlaw events that are useless and not needed but a burden on the memory as they are sill listening for events.
They can happen on both client and server.

To prevent thrm you can use the :Once method, rather than the :Connect method for events that only fire once or just disconnect your method as soon so they are not needed. Do note that if a script gets destroyed the events running in that script will also stop.

2 Likes

What are the consequences of memory leaks on both server and client?

They just hogg memory. On server too many leaks can cause the server to crash and lose performance and for the client it reduces performance. It’s best to try and fix them.

This connection will automatically be disconnected. When a player leaves, their Player object is destroyed, and all the objects parented to that Player object will also be destroyed. And when an Instance gets destroyed, all connections to that Instance are disconnected automatically. So you don’t have to worry a lot here.

If you want, you can create a connection table, add the created connection to this table, and disconnect and remove it from the table once the player leaves.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.