Garbage-free, performant object pooling

It’s often recommended to use object pooling to reduce garbage generation. The problem is, I don’t know how to do so without generating garbage.

I tried an implementation where I have a ConcurrentBag<T> containing instances available for reuse, and a LinkedList<T> (for O(1) removal) containing instances that are currently in use. The problem is, the LinkedList generates garbage.

Would I need to use an array instead, where indices in the array are set to null if unused, and then have to instantiate a new array if the collection of in-use objects grows too large to fit?

Something about a growing array, you would still be disposing of a large array when growing it by a percentage, but you would grow it by enough to reduce the garbage amount at each growth…

Meaning you create an array of 1000 objects, you populate 80%, you then clear on the next addition, or something copy the array to a new list, and increment it by say 20% above the added items or something…

I have been thinking to create content on these operations, but it can take time for that to fruit…

Hopefully, that made sense, basically: array with space to grow, and then grow it further with space to grow between each new array being created… I need to brush up on this aspect…

I think this was a performant aspect and not a garbage reduction though that was a side effect to a degree…

1 Like

I ended up using an array, for first and last item indices as an optimization.

1 Like