A probably obvious question about generics

Don't hate me because I'm ignorant... remember that I don't have a formal programming background. If I'm to understand generics correctly, using System.Collections.Generic.List<T> will be ridiculously faster than using an ArrayList, because everything is boxed/unboxed to and from an object in an ArrayList, right? Whereas List<T> is a collection of objects that are a predictable type?

In a related question, is BinarySearch() still the best method to find objects that have a particular property value? And I assume that the type I'm searching has to implement IComparer?

2 Comments

  • generics will be faster because of no boxing for valuetypes, *in most cases*



    basically you'll notice the biggest difference in methods that iterate the arraylist of valuetype-derived classes (int, decimal, System.Drawing.Color, etc)



    and yes BinarySearch is still the fastest, only when the arraylist is properly balanced... binarysearch could possibly be the slowest if the array has items in a particular order... but in most cases, yes binarySearch is fastest

  • List&lt;T&gt; is faster than ArrayList, for at least three reason:

    1) Casting (an expensive operation) is optimized away

    2) Boxing and memory allocation is eliminated for value types

    3) Methods calls on generic lists are direct, rather than virtual



    BinarySearch is faster than IndexOf for large lists, but it only works on sorted lists, and the type has to implement IComparable&lt;T&gt; or IComparable.

Comments have been disabled for this content.