ArrayList vs List<> in C#

后端 未结 12 1980
深忆病人
深忆病人 2020-11-22 04:10

What is the difference between ArrayList and List<> in C#?

Is it only that List<> has a type while ArrayLis

12条回答
  •  囚心锁ツ
    2020-11-22 05:05

    Performance has already been mentioned in several answers as a differentiating factor, but to address the “How much slower is the ArrayList ?” and “Why is it slower overall ?”, have a look below.

    Whenever value types are used as elements, performance drops dramatically with ArrayList. Consider the case of simply adding elements. Due to the boxing going on - as ArrayList’s Add only takes object parameters - the Garbage Collector gets triggered into performing a lot more work than with List.

    How much is the time difference ? At least several times slower than with List. Just take a look at what happens with code adding 10 mil int values to an ArrayList vs List:

    That’s a run time difference of 5x in the ‘Mean’ column, highlighted in yellow. Note also the difference in the number of garbage collections done for each, highlighted in red (no of GCs / 1000 runs).

    Using a profiler to see what’s going on quickly shows that most of the time is spent doing GCs, as opposed to actually adding elements. The brown bars below represent blocking Garbage Collector activity:

    I’ve written a detailed analysis of what goes on with the above ArrayList scenario here https://mihai-albert.com/2019/12/15/boxing-performance-in-c-analysis-and-benchmark/.

    Similar findings are in “CLR via C#” by Jeffrey Richter. From chapter 12 (Generics):

    […] When I compile and run a release build (with optimizations turned on) of this program on my computer, I get the following output.

    00:00:01.6246959 (GCs= 6) List
    00:00:10.8555008 (GCs=390) ArrayList of Int32
    00:00:02.5427847 (GCs= 4) List
    00:00:02.7944831 (GCs= 7) ArrayList of String

    The output here shows that using the generic List algorithm with the Int32 type is much faster than using the non-generic ArrayList algorithm with Int32. In fact, the difference is phenomenal: 1.6 seconds versus almost 11 seconds. That’s ~7 times faster! In addition, using a value type (Int32) with ArrayList causes a lot of boxing operations to occur, which results in 390 garbage collections. Meanwhile, the List algorithm required 6 garbage collections.

提交回复
热议问题