I have been asked to revise the code written some time ago for a windows form application. The programmer has used ArrayList heavily. I think generic lists are way more efficient compared to array lists and plan to rewrite the code using List<T> I wanted to know if there are any other alternatives that might also be worth considering. I work on .net 2.0
If you're working in .NET 2, then you won't have any of the concurrent collections in .NET 4 available to you, which pretty much just leaves List<T> in terms of "collections which are a bit like ArrayList. (Even within the concurrent collections, there isn't an immediate equivalent - and you should only use the concurrent collections when you actually anticipate concurrent access anyway.)
There are Stack<T> and Queue<T>, as well as LinkedList<T> - but all of those are somewhat different to ArrayList in terms of what you can do with them. They're worth considering if you don't need random access, of course.
I wouldn't expect too much more in terms of efficiency unless you're currently boxing a lot of large value types in your ArrayList. What you can expect is far clearer code. Fewer casts, less uncertainty about the contents of the collection, etc.
If you have the option of upgrading to .NET 3.5 at any point in the near future, that would then give you access to LINQ, which is fabulously useful when dealing with collections. Relatively few new collection types, but much simpler ways of expressing operations on them.
Update:
For add to/remove from head/tail it is better to use LinkedList<T>, but if you can determine exact maximum capacity of collection and size will be close to capacity then may be it's better to use Queue<T> (because internally it's array, reallocated when size reaches capacity). With Queue you will not get memory overhead that comes with LinkedList nodes.
Original:
From MSDN: The List<T> class is the generic equivalent of the ArrayList class.
Please, read carefully List<T> Performance Considerations section.
What should you use depends on how ArrayList is used? Is it random access or add to/remove from head/tail?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With