Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is converting this ArrayList to a Generic List efficient?

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?

like image 746
Greg Avatar asked Jun 07 '10 18:06

Greg


2 Answers

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.

like image 101
Amy B Avatar answered Sep 23 '22 05:09

Amy B


I often use this checklist to evaluate questions like yours:

  1. Make it correct
  2. Make it clear
  3. Make it concise
  4. Make it efficient

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.

like image 27
Bryan Watts Avatar answered Sep 20 '22 05:09

Bryan Watts