Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to iterate over a stack in c#

I feel that using GetEnumerator() and casting IEnumerator.Current is expensive. Any better suggestions?

I'm open to using a different data structure if it offers similiar capabilities with better performance.

After thought:
Would a generic stack be a better idea so that the cast isn't necessary?

like image 371
Adam Naylor Avatar asked Oct 31 '08 09:10

Adam Naylor


Video Answer


1 Answers

If you need the functionality of a Stack (as apposed to a List, or some other colleciton type), then yes, use a generic stack. This will speed things up a bit as the compiler will skip the casting at runtime (because it's garunteed at compile time).

Stack<MyClass> stacky = new Stack<MyClass>();

foreach (MyClass item in stacky)
{
    // this is as fast as you're going to get.
}
like image 88
Timothy Khouri Avatar answered Oct 16 '22 21:10

Timothy Khouri