I was wondering how you could improve performance of loops in module scripts all running in parallel.
For example: My current approach was doing this:
function module.DoStuff()
-- do stuff here idk
task.wait(5)
module.DoStuff()
end
function module.Start()
coroutine.wrap(module.DoStuff)()
end
Basically I would call the so stuff function from inside the function to create an infinite loop.
That alone works but image 100 of these running in parallel. I found that causing quite the lag on the server + unevenly delaying the loop as well.
Here are 2 approaches I thought of that might improve the performance and prevent less delays but I don’t know if they really are that good. Could someone tell me which one is better / what to improve?
Method 1:
--Essentially my current approach but functionality is split into many different modules which are also coroutine.wraped to put the work onto different threads and hopefully decrease delays
Method 2:
function module.Start()
coroutine.wrap([Other module script].DoStuff)()
end
-- Other module script
function module.DoStuff()
while task.wait(5) do
-- do stuff
end
end
Not really all functions. Just one function on an endless loop. I was looking for a way to achieve this in an as optimized way as possible because I found the server lagging a lot when the function was calling itself in let’s say 0.25 sec succession. (My current approach)
I’d prefer an iterative approach over recursion. I think you have a misconception though, threads from the coroutine/task library cooperatively multitask. They are not in parallel and cannot run at the exact same genuine time. Also keep the call to task.wait within the loop body, use true as the condition for an infinite loop.
These work but, they are not optimized.
Focusing on optimization while still being scalable:
local tasks = {}
function module.DoStuff(task)
--
end
function module.Start(task)
table.insert(tasks, task)
end
coroutine.wrap(function()
while true do
for _, task in pairs(tasks) do
module.DoStuff(task)
end task.wait(5)
end
end)()
coroutine.wrap(function()
while true do
--asfgfdhgjgkfdj
task.wait(5)
end
end)()
would be the fastest, strictly based on performance
you could also use RenderStepped(client)/Stepped(server) loops and os.clock() for more(practically unnecessary) precision for when the function is called