- Home /
Using Stack vs A list in my pool script
Hello! I've made plenty pool systems for many games I've worked on. I started work on a new project and I created a pool system. However for some reason I decided to do some reading on pooling because I was interested in how other did their systems. I found that many used Stack over something like a list or an array list. I never used stack but what I want to know is... is stack better for performance in a pool system or something like a list or array would be better. Thanks!
Answer by Bunny83 · Apr 05, 2019 at 09:20 PM
Both the Stack and the List use a native array internally. It doesn't really matter if you use a List or a Stack, though it depends on how you use them. For example Adding to the end of the list or removing from the end is as cheap as Stack push / pop. However if you remove the first element in the list you get a lot of overhead since every remove operation has to move all remaining elements around
What if I removed the LAST object in the List? Would it still move all the items in the list?
Curiously, would it be more efficient (in a list) to swap the element you are intending to remove with the last element in the last, and then removing the last element? If the usage of the order of elements doesn't matter that is.
Yes, of course. This is actually a common solution if arbitrary elements need to be removed and the order doesn't matter. Though you actually don't need to swap them. Just copy the last element over the element you want to remove and then drop the last element. A List is essentially just a wrapper class for an ordinary array. It only has an additional integer field to remember the current element count. $$anonymous$$ethods like Add may create a new internal array if the current array capacity isn't large enough for the newly added value. Removing the last element essentially just sets the last element to null (default(T)) and decrements the count.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
how to create random list of two diffrent prefab 1 Answer
How to increase rate of a falling object in pooling object? 1 Answer
How to pull two objects at the same time? 0 Answers
Object Pooling for Class Pattern 0 Answers