Will spamming coroutines lag the server?

I am currently writing a script which controls the behaviour and actions of several npcs.
For performance reasons I am controlling all the npcs in one loop (rather than 10+ individual while loops in each npc).

while true do task.wait(0.1125)
    for _ in pairs(AIStore) do -- where the npcs are kept
        coroutine.resume(coroutine.create(function()
            -- control npcs..
        end)
    end
end

this while loop runs in 0.1 seconds and then loops over a table containing 10-25 npcs. This script is done on the server.

My question is, will spamming this much coroutines lag the server over time (or affect the clients performance) and if so are there any alternatives?

1 Like

Only way to know for sure is to try it! :smiley:

On a more serious note though, spamming anything will eventually lag the server, but optimizations and multi-threading is definitely the way to go to get a “lag free” experience. Is there any reason this is done on both the server and the client?

It was a mistake on my part, I edited the post to make it more clearer.

The script is only done on the server.

I gave some suggestions over in the thread below, perhaps these may be helpful.

Combining this with what you already got may be able to provide a significant bump in humanoids before they become laggy.

i tested spamming coroutines in studio and nothing changed

Sounds like there might be slight benefits from saving coroutines and using coroutine.close()? API reference isn’t super clear on what a “dead state” is but could free up memory over time.

2 Likes