Will this script create a memory leak?

Hello, I was wondering if this code would create a memory leak.

local Car = game.ServerStorage.Car

local function SpawnCar()
	local NewCar = Car:Clone()
	NewCar.Parent = workspace
end

local function DeleteCar()
	workspace.Car:Destroy() -- "New car" is destroyed
end

SpawnCar()
task.wait(10)
DeleteCar()
-- Memory leak?
-- New car is never set to nil but it is being destroyed

If the script ends there then the car should get garbage collected.

No, as it sets its parent to nil when you destroy it

What about something like this?

-- Module script

local Car = game.ServerStorage.Car
local Module = {}

function Module.SpawnCar()
	local NewCar = Car:Clone()
	NewCar.Parent = workspace
end

function Module.DeleteCar()
	workspace.Car:Destroy()
end

-- Server script

local Module = require(script.Parent)
for i = 1, 100000 do
	Module.SpawnCar()
	task.wait(10)
	Module.DeleteCar()
end

Sorry, I misread your code before; the car would’ve been garbage collected regardless of whether the script had ended.

So I don’t need to set new car to nil?

yeah, car:Destroy() will automatically garbage the object, as it sets car.Parent to nil

1 Like

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