Does this use of for loop will cause a memory leak?

I don’t know any other exact way to explain it so that it’s understood correctly so i’ll just write an example code.

local Contents = script.Parent.Gui:GetChildren() -- 36 children
for _,v in ipairs(Contents) do
   print(tostring(v)) -- prints 36x
   v.InputBegan:Connect(function()
   print("Start 30+ lines of code") -- Gets created 36x on 36 functions
   print("Start 10+ lines of code") --  Gets created 36x on 36 functions
   print("Pause some 5+ lines of code") -- Gets created 36x on 36 functions
end

-- vs
local function foo(v)
   local current = v
   print("Start 30+ lines of code") -- Gets created only once.
end

for _,v in ipairs(Contents) do
   print(tostring(v)) -- prints 36x
   v.InputBegan:Connect(function()
   foo(v) -- Gets created 36x on 36 functions
   end
end

If you look at the top, it seems to be way more expensive.

Will this code a memory leak?

Well you can always Disconnect events you don’t need anymore to then connect the new ones. But in the scenario you have right now, doesn’t look like there’s a memory leak (unless you keep connecting multiple events to it)

I don’t really see a difference between both? Try explaining it more.

The for loop on the first one will loop 36x creating 36 different Connections with the same code except different instance being called on that loop. The loop creates those codes 36x because the loop is running 36x on them.

While on the second one the codes are written inside a function which is only created once but called 36x with different arguments.

I’m saying all connections are referencing the same codes and not creating those same codes by themselves.

When you call a function, it runs normally. The function is not pre ran when created so you would have the same scenarios in both cases.

local function foo(x)
    print('a')
end
for i = 1, 30 do
    foo(x) -- Takes the foo function and runs it here
end

-- Same as

for i = 1, 30 do
    print('a')
end

I’m saying all connections are referencing the same codes and not creating those same codes by themselves.

Ok that’s what I don’t understand.

local Contents = script.Parent.Gui:GetChildren() -- 36 children
for _,v in ipairs(Contents) do
   print(tostring(v)) -- prints 36x
   v.InputBegan:Connect(function()
   print("Start 30+ lines of code") -- Gets created 36x on 36 functions
   print("Start 10+ lines of code") --  Gets created 36x on 36 functions
   print("Pause some 5+ lines of code") -- Gets created 36x on 36 functions
end

Over there in your code, you are starting the InputBegan signal, but then tell us that you will create 2 others?

Well if you see there’s no problem with it then I guess there’s no problem with it then.

1 Like