So I have some heavy procedural stuff in my code- I add and remove lot’s of (thousands) parts. For example the removing:
function Octree:CleanDelQueue()
for n = 1, #self.delQueue, 1 do
self.delQueue[n]:Destroy()
end
self.delQueue = {}
end
This created big lag/freeze in my game. Are there some strategies to avoid those? Like maybe hiding all parts and then destroying in background with wait? And what about adding? Maybe add hidden parts with wait and then change transparency 1 run?
Yes, you can use an “object pool” to avoid constantly creating and destroying objects. There are roblox specific implementations if you search around, don’t know how good they are.
Essentially, instead of using Instance.new and Instance.Destroy, you use ObjectPool.LoanObject and ObjectPool.ReturnObject. If the pool has no more unused objects to loan out, it grows the pool by adding objects in the usual way, with Instance.new. Once an object is returned it doesn’t get destroyed, it’s just “put somewhere safe” for later use and marked as unused. When LoanObject is called and there are unused objects in the pool, those objects are returned instead. If your code has a lot of object creation, and destruction interweaved, you can save some time setting up and cleaning up those objects. If you have a lot of creation and then a lot of destruction, it won’t actually save you any time.
If you go with an object pool, you want the loaning and returning to be as cheap as possible. So don’t “reset” all the properties when that happens, just let the user code be responsible for setting any necessary properties after LoanObject returns. You might want to set Parent to nil tho, but if I were you I’d experiment with using WorldRoot | Roblox Creator Documentation and see if that’s faster than setting every Parent to nil. If you just keep a table ready with the CFrames and reuse that instead of setting it up every time ReturnObject is called, that should be a bit of a performance gain. Only testing will show though.