Hello developers,
Recently, I’ve been trying to ‘optimize’ my code to save memory.
Here’s how I’ve done it:
When I use Loops, Many Threads, or RunService functions, I try to keep the variables Outside of the loop/thread/function, to not create too many variables (mass in memory).
This way, every time a new iteration uses the variable, the variable is given a new value to store.
Here’s an example:
(Please ignore the fact the prints can lag/take time too, I only put it there for the demonstration)
1.Non-Optimized Scripting:
for i = 1, 10000000,1 do
local num = i / 5 --The variable is created 10000000 times. That means it has to be stored 10000000, and then garbage-collected 10000000.
print(num)
end
game:GetService("RunService").Heartbeat:Connect(function(deltaTime)
local deltaOperations = math.abs(deltaTime * -1 * 10000 * -123142 * math.pi) --Some operations on the deltaTime.
--The variable is created EVERY heartbeat, which means lots of variables to be stored, then garbage collected.
print(deltaOperations)
end)
SomePart.Touched:Connect(function(hit)
local char = hit:FindFirstAncestorWhichIsA("Model") --The Touched event can run a LOT on each and every small movement, and is known to fire rapidly.
--Again, the variable is created a massive amount of times, and then stored, garbage collected, etc.
print(tostring(char))
end)
Here, the variable is created when needed, in every thread/function/loop/etc. But the more variables created, the more memory to be stored and collected.
2. Optimized Scripting:
local num
for i = 1, 10000000,1 do
num = i / 5 --The variable is changed 10000000 times. That means it has to be stored 1 time, and then garbage-collected 1 time after the loop.
print(num)
end
local deltaOperations
game:GetService("RunService").Heartbeat:Connect(function(deltaTime)
deltaOperations = math.abs(deltaTime * -1 * 10000 * -123142 * math.pi) --Some operations on the deltaTime.
--The variable is created Before the first heartbeat, which means only 1 variable will be stored, then garbage collected.
print(deltaOperations)
end)
local char
--(I didn't implement a debounce on purpose)
SomePart.Touched:Connect(function(hit)
char = hit:FindFirstAncestorWhichIsA("Model") --The Touched event can run a LOT on each and every small movement, and is known to fire rapidly.
--Again, the variable is created one time, and then stored, garbage collected, etc.
print(tostring(char))
end)
The difference is that here, the variable is only created once, and used for how many times we need, to not overload the memory and garbage-collector.
But is it really necessary? Does it make an impact? Or am I just optimizing for nothing (Since the non-optimized way is much easier to do)?
Thanks in advance.