ArrayList vs List<object>

前端 未结 6 1558
夕颜
夕颜 2020-11-27 17:43

I saw this reply from Jon on Initialize generic object with unknown type:

If you want a single collection to contain multiple unrelated types of v

相关标签:
6条回答
  • 2020-11-27 18:22

    List<> is a typesafe version of ArrayList. It will guarantee that you will get the same object type in the collection.

    0 讨论(0)
  • 2020-11-27 18:31

    One big benefit to using List<object> is that these days most code is written to use the generic classes/interfaces. I suspect that these days most people would write a method that takes a IList<object> instead of an IList. Since ArrayList doesn't implement IList<object> you wouldn't be able to use an array list in these scenarios.

    I tend to think of the non-generic classes/interfaces as legacy code and avoid them whenever possible.

    0 讨论(0)
  • 2020-11-27 18:34

    Do some benchmarking and you will know what performs best. I guestimate that the difference is very small.

    0 讨论(0)
  • 2020-11-27 18:36

    Yes, besides being typesafe, generic collections might be actually faster.

    From the MSDN (http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx)

    The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

    0 讨论(0)
  • 2020-11-27 18:39

    You'll be able to use the LINQ extension methods directly with List<object>, but not with ArrayList, unless you inject a Cast<object>() / OfType<object> (thanks to IEnumerable<object> vs IEnumerable). That's worth quite a bit, even if you don't need type safety etc.

    The speed will be about the same; structs will still be boxed, etc - so there isn't much else to tell them apart. Except that I tend to see ArrayList as "oops, somebody is writing legacy code again..." ;-p

    0 讨论(0)
  • 2020-11-27 18:39

    In this case, ArrayList vs. List<Object> then you won't notice any differences in speed. There might be some differences in the actual methods available on each of these, particular in .NET 3.5 and counting extension methods, but that has more to do with ArrayList being somewhat deprecated than anything else.

    0 讨论(0)
提交回复
热议问题