How to use object pooling?

In other game engines, object pooling is creating lots of objects at the start of a scene, then reusing them instead of destroying them. How can you do that with Defold?

This practice is not necessary in Defold. It’s automatically done for you. The reason why it’s automatic is that in your game.project you set the max of everything you want, and then those are reused.

Create/destroy objects at will. There is no issue for this in Defold.

4 Likes

As @Pkeod says there really is no need to manually pool your objects. I created an example a long time ago that shows this: publicexamples/examples/pooling_vs_creating at master · britzl/publicexamples · GitHub

1 Like

Is there a performance hit in setting really high limits in game.project?

It will allocate more memory. But if you set 10000 as limit and use only 10 it would not traverse all 10000 so from an update perspective there shouldn’t be any difference.

4 Likes

A recommendation is to never set higher limits than you know that you will use. Use the profiler or make manual calculations and then set limits based on your findings.

3 Likes

Thanks, that’s a great idea!

1 Like

I downloaded the benchmark out of curiosity and tried to eliminate as many variables as possible that could affect the result. My findings are that it does make a difference when you’re dealing with thousands of game objects.

On average it is twice as fast to move game objects in and out of a pool, than creating and destroying them. However, it uses up almost twice the memory. That could be because of my implementation though, where I move the IDs from an active and inactive pool. The results are very consistent and only fluctuates roughly 1kB and at most 1ms.

2500 Pooled game objects
Time: 3ms
Memory: 350.94kB.

2500 Created/Deleted game objects
Time: 6ms
Memory: 194.68kB

image

It takes roughly 3 runs for the memory to stabilize. The first and second run can fluctuate a bit.

Ran it on this system
CPU: 13th Gen Intel(R) Core™ i5-1335U (1.30 GHz)
RAM: 16,0 GB
iGPU: Intel(R) Iris(R) Xe Graphics (128 MB)
Defold version: 1.13.0

I hope this can be helpful to anyone in the future. :slight_smile:

1 Like

Just guessing, but the time difference is probably because of the Lua → C overhead. AFAIK, they are not allocated and freed on the C side for every GO create/delete, they are already pooled. If you try creating and deleting them entirely in C using the SDK, you’ll probably get less than half the Lua. I don’t know how you profiled them, but those numbers also seem a little too high to me.

Yes that would be my assumption too.

I started it with the benchmark linked to in this thread, then I tried to strip it down as much as possible, localizing global functions, and reusing tables, removing animations, etc.

The initial benchmark used more CPU and memory, roughly 9ms and 1MB for the create/delete code path.