The code I'm writing receives an ArrayList from unmanaged code, and this ArrayList will always contain one or more objects of type Grid_Heading_Blk. I've considered changing this ArrayList to a generic List, but I'm unsure if the conversion operation will be so expensive as to nullify the benefits of working with the generic list. Currently, I'm just running a foreach (Grid_Heading_Blk in myArrayList)
operation to work with the ArrayList contents after passing the ArrayList to the class that will use it.
Should I convert the ArrayList to a generic typed list? And if so, what is the most efficient way of doing so?
Here's a stab at a performant way to create a generic list from an ArrayList.
List<Grid_Heading_Blk> myList = new List<Grid_Heading_Blk>(source.Count);
myList.AddRange(source.OfType<Grid_Heading_Blk>());
By calling the constructor that accepts an int, the backing storage is allocated only once.
As always, you should measure the performance using whatever tools you normally use.
I often use this checklist to evaluate questions like yours:
List<Grid_Heading_Blk>
is far more intention-revealing than ArrayList
. So, without even considering efficiency, there is already a big win for item 2.
To convert an ArrayList
to a List<>
, you have to iterate over the ArrayList
once and cast each element. The foreach
is doing an implicit cast, so the overhead is only in the extra iteration.
Iterating a sequence twice takes the performance from O(n)
to O(2n)
, which is still O(n)
(magnitude, not value, is what matters for performance). Therefore, you can consider the change benign.
However, if literally all you are doing is running the foreach
, you should just use ArrayList
directly - changing it to List<>
buys you no more expressive power.
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