Object Pooling: Dict<enum, List<T>> vs. Switch statement and several Lists<T>

Hello!

Hopefully those more knowledgeable than I can give some insight.

I realize that at the sizes of Dictionary Keys/Lists I’m going to be using that most likely either isn’t enough to warrant performance concerns (a handful of Enum keys and maybe a couple hundred per list at most). But I’m curious of which you think would be the better solution or if ultimately it really doesn’t matter since performance will most likely be similar in either case. Or maybe there is an upside or downside to one over the other or maybe even a solution I didn’t think of!

As stated in the title I’m object pooling, specifically bullets. I have different bullet types thus the Enum to help identify which bullet I’m wanting to grab.

I would prefer the first option with a Dictionary. Firstly, it’s a flexible choice; when adding a new type to the enum, the code for retrieving from the dictionary won’t change. Additionally, accessing by key should be faster (that’s also the dictionary’s advantage). Using a switch statement would require adding cases when the enum changes, and a switch statement involves iterating through elements, which means it’s a bit slower. I might be mistaken, but my bet is on the Dictionary.

2 Likes

Don’t reinvent the pool. :wink:

Unity has ObjectPool and a couple related classes:

And this free asset wraps this API quite nicely:

It’s very use case and compiler dependent. In .NET a switch can be faster with a small number of entries.

https://stackoverflow.com/questions/11617091/in-a-switch-vs-dictionary-for-a-value-of-func-which-is-faster-and-why

It’s definitely a micro-optimization. You won’t likely see an impact from choosing one over the other.

4 Likes