Is it better to call ToList() or ToArray() in LINQ queries?
Asked Answered
B

17

625

I often run into the case where I want to eval a query right where I declare it. This is usually because I need to iterate over it multiple times and it is expensive to compute. For example:

string raw = "...";
var lines = (from l in raw.Split('\n')
             let ll = l.Trim()
             where !string.IsNullOrEmpty(ll)
             select ll).ToList();

This works fine. But if I am not going to modify the result, then I might as well call ToArray() instead of ToList().

I wonder however whether ToArray() is implemented by first calling ToList() and is therefore less memory efficient than just calling ToList().

Am I crazy? Should I just call ToArray() - safe and secure in the knowledge that the memory won't be allocated twice?

Breadfruit answered 9/7, 2009 at 19:28 Comment(0)
C
464

Unless you simply need an array to meet other constraints you should use ToList. In the majority of scenarios ToArray will allocate more memory than ToList.

Both use arrays for storage, but ToList has a more flexible constraint. It needs the array to be at least as large as the number of elements in the collection. If the array is larger, that is not a problem. However ToArray needs the array to be sized exactly to the number of elements.

To meet this constraint ToArray often does one more allocation than ToList. Once it has an array that is big enough it allocates an array which is exactly the correct size and copies the elements back into that array. The only time it can avoid this is when the grow algorithm for the array just happens to coincide with the number of elements needing to be stored (definitely in the minority).

EDIT

A couple of people have asked me about the consequence of having the extra unused memory in the List<T> value.

This is a valid concern. If the created collection is long lived, is never modified after being created and has a high chance of landing in the Gen2 heap then you may be better off taking the extra allocation of ToArray up front.

In general though I find this to be the rarer case. It's much more common to see a lot of ToArray calls which are immediately passed to other short lived uses of memory in which case ToList is demonstrably better.

The key here is to profile, profile and then profile some more.

Chartism answered 1/5, 2013 at 17:42 Comment(12)
On the other hand, wouldn't the extra memory allocated for the legwork of creating the array be eligible for garbage collection, whereas the extra overhead for the List would remain? I say keep it simpler. If you need to add or remove elements, there's a tool for that. If you don't, there's a different tool for that. Use the one that makes sense. If later on, you discover an issue with memory and performance, and this is it, change it.Cabala
@AnthonyPegram yes that is a valid consideration to make. If the value is being used in long term storage, won't be modified, and potentially will make it into Gen 2 then you may be better off paying the extra allocation now vs polluting the Gen 2 heap. IME though I rarely see this. It's much more common to see ToArray being passed immediately to another short lived LINQ query.Chartism
@Chartism If all you want to do is resolve the enumerable to a fixed collection for iteration, how does ImmutableList<T> stack against List<T> and T[]?Kurt
@Chartism Exist any reason to do: query.ToArray().ToList() I saw this in @miguelcastro67 method named ToFullyLoaded<T>(this IQueryable<T> query)Higgins
@zerazobz ToList is great if you want to further edit the values for exampleChartism
@Chartism I don't understand how ToArray Can allocate more memory if it needs the exact locations size where ToList<> obviously has it's automatic spare locations. (autoincrease)Boccherini
@RoyiNamir because ToArray first does the ToList-style allocations with overhead, then does an additional exact-size allocation.Airframe
So, if ToArray actually costs more memory than ToList, what do you use when you want an IEnumerable list? AsEnumerable() doesn't resolve the SQL right away, and that's a problem when you are searching your collection instead of iterating over it.Semilunar
Looking at the sourecode of both ToArray and ToList i can't see how you conclude that ToList is better. Both start with an array of 4 and double its size when its needed. ToList wont trim the excess once its done, but there is an extra method for it. ToArray will however make sure it only uses exactly the ammount of required memory. So ToArray uses one more allocation, but ToList might allocate way too much space in a worst case where the last element needs a new allocation.Lag
In corefx there are not more cases where both ToArray() and ToList() figures out the size up front, and hence ToArray() is the slightly lighter. It still wouldn't benefit the example in the question, because the Where means such prediction can't be done.Topography
There's no substitute to understanding what's really going on (which this answer describes well), because even after burning all the hours to profile, profile and then profile some more, outside of the hotspots, the death by a thousand papercuts of all the ToArrays that could have been ToLists won't stand out. Well, maybe it's more like "lackluster performance by a thousand papercuts", but either way, profiling can't help much with broadly scattered slowness.Burck
Is this statement still true anno 2023? Since C# /.Net has had many performance improvements over the years.Crosseyed
H
177

The performance difference will be insignificant, since List<T> is implemented as a dynamically sized array. Calling either ToArray() (which uses an internal Buffer<T> class to grow the array) or ToList() (which calls the List<T>(IEnumerable<T>) constructor) will end up being a matter of putting them into an array and growing the array until it fits them all.

If you desire concrete confirmation of this fact, check out the implementation of the methods in question in Reflector -- you'll see they boil down to almost identical code.

Haemophilic answered 9/7, 2009 at 19:33 Comment(7)
In Entity-Framework there is an option for eager reloading using EntityCollection.CreateSourceQuery, where sometimes I am actually discarding the results, then I think it's more proper to use ToArray.Charlacharlady
An interesting fact that I came across is that for correlated queries caused by using a group defined through a group join in your projection causes Linq to SQL to add another sub-query to retrieve the count for that group. I'm assuming that this means in these cases the size of the collection will be known before the items are retrieved and thus an exact sized array could be created directly which would save on processing and memory resources while materializing the results.Mulloy
If the Count is known in advance, the performance is identical. However, if the Count isn't known in advance, the only difference between ToArray() and ToList() is that the former has to trim the excess, which involves copying the entire array, whereas the latter doesn't trim the excess, but uses an average of 25% more memory. This will only have implications if the data type is a large struct. Just food for thought.Delegacy
@ScottRippey Why 25%? How do you get that number?Lahnda
@EldritchConundrum 25% comes from this logic: If the number of items is unknown, then calling ToList or ToArray will start by creating a small buffer. When that buffer is filled, it doubles the capacity of the buffer and continues. Since the capacity is always doubled, the unused buffer will always be between 0% and 50%.Delegacy
@ScottRippey I just looked up the source of new List from IEnumerable source, and it checks if the IEnumerable is an ICollection, and if it is, then it starts out by allocating one array with the exact size needed from the Count property, so this would be the case where ToList() would definitely be faster. A complete answer could include that fact, although I don't think it is the most common case.Swiercz
@Swiercz Both List and Buffer will check for ICollection, in which case the performance will be identical.Delegacy
L
129

EDIT 2: (this is a correction for the original answer)

Using Benchmark.NET we could confirm with performance measurements, that the accepted answer is actually correct: ToList is faster in the general case, because it doesn't have to trim the empty space from the allocated buffer. ToArray might do an additional allocation and copy operation such that the buffer will be sized exactly to the number of elements.

In order to confirm this the following benchmark is used.

[MemoryDiagnoser]
[ShortRunJob]
public class Benchmarks
{
    [Params(0, 1, 6, 10, 42, 100, 1337, 10000)]
    public int Count { get; set; }

    public IEnumerable<int> Items => Enumerable.Range(0, Count).Where(i => i > 0);

    [Benchmark(Baseline = true)]
    public int[] ToArray() => Items.ToArray();

    [Benchmark]
    public List<int> ToList() => Items.ToList();
}

The results confirm that ToList is in most cases 10% - 15% faster.

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000
Intel Core i9-10885H CPU 2.40GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK=6.0.302
  [Host]     : .NET 6.0.7 (6.0.722.32202), X64 RyuJIT
  DefaultJob : .NET 6.0.7 (6.0.722.32202), X64 RyuJIT


|  Method | Count |         Mean |      Error |     StdDev | Ratio | RatioSD |   Gen 0 |  Gen 1 | Allocated |
|-------- |------ |-------------:|-----------:|-----------:|------:|--------:|--------:|-------:|----------:|
| ToArray |     0 |     29.73 ns |   0.546 ns |   0.536 ns |  1.00 |    0.00 |  0.0067 |      - |      56 B |
|  ToList |     0 |     31.51 ns |   0.485 ns |   0.405 ns |  1.06 |    0.02 |  0.0105 |      - |      88 B |
|         |       |              |            |            |       |         |         |        |           |
| ToArray |     1 |     37.36 ns |   0.314 ns |   0.294 ns |  1.00 |    0.00 |  0.0114 |      - |      96 B |
|  ToList |     1 |     36.75 ns |   0.605 ns |   0.537 ns |  0.98 |    0.01 |  0.0153 |      - |     128 B |
|         |       |              |            |            |       |         |         |        |           |
| ToArray |     6 |    100.05 ns |   1.522 ns |   1.349 ns |  1.00 |    0.00 |  0.0286 |      - |     240 B |
|  ToList |     6 |     85.16 ns |   0.808 ns |   0.756 ns |  0.85 |    0.01 |  0.0267 |      - |     224 B |
|         |       |              |            |            |       |         |         |        |           |
| ToArray |    10 |    137.20 ns |   2.766 ns |   2.452 ns |  1.00 |    0.00 |  0.0372 |      - |     312 B |
|  ToList |    10 |    123.05 ns |   2.198 ns |   1.949 ns |  0.90 |    0.01 |  0.0372 |      - |     312 B |
|         |       |              |            |            |       |         |         |        |           |
| ToArray |    42 |    398.25 ns |   6.583 ns |   5.836 ns |  1.00 |    0.00 |  0.0877 |      - |     736 B |
|  ToList |    42 |    352.04 ns |   4.976 ns |   4.411 ns |  0.88 |    0.02 |  0.0887 |      - |     744 B |
|         |       |              |            |            |       |         |         |        |           |
| ToArray |   100 |    730.80 ns |   6.501 ns |   6.081 ns |  1.00 |    0.00 |  0.1488 |      - |   1,248 B |
|  ToList |   100 |    705.49 ns |   9.947 ns |   9.305 ns |  0.97 |    0.01 |  0.1526 |      - |   1,280 B |
|         |       |              |            |            |       |         |         |        |           |
| ToArray |  1337 |  8,023.57 ns | 147.388 ns | 137.867 ns |  1.00 |    0.00 |  1.6785 | 0.0458 |  14,056 B |
|  ToList |  1337 |  7,980.27 ns | 138.469 ns | 122.749 ns |  1.00 |    0.02 |  1.9989 | 0.1221 |  16,736 B |
|         |       |              |            |            |       |         |         |        |           |
| ToArray | 10000 | 57,037.19 ns | 510.492 ns | 452.538 ns |  1.00 |    0.00 | 12.6343 | 1.7700 | 106,280 B |
|  ToList | 10000 | 57,728.15 ns | 583.353 ns | 517.127 ns |  1.01 |    0.01 | 15.5640 | 5.1270 | 131,496 B |

For reference, following below is the original answer which unfortunately performed a benchmark on a very particular case only, which avoided intermediate resize and copy operations.

ORIGINAL ANSWER:

It's 2020 outside and everyone is using .NET Core 3.1 so I decided to run some benchmarks with Benchmark.NET.

TL;DR: ToArray() is better performance-wise and does a better job conveying intent if you're not planning to mutate the collection.

EDIT: as seen from the comments, these benchmarks might not be indicative because Enumerable.Range(...) returns an IEnumerable<T> that has information about the size of the sequence, which is subsequently used in an optimization by ToArray() to pre-allocate an array of the correct size. Consider testing performance manually for your exact scenario.


    [MemoryDiagnoser]
    public class Benchmarks
    {
        [Params(0, 1, 6, 10, 39, 100, 666, 1000, 1337, 10000)]
        public int Count { get; set; }
    
        public IEnumerable<int> Items => Enumerable.Range(0, Count);
    
        [Benchmark(Description = "ToArray()", Baseline = true)]
        public int[] ToArray() => Items.ToArray();
    
        [Benchmark(Description = "ToList()")]
        public List<int> ToList() => Items.ToList();
    
        public static void Main() => BenchmarkRunner.Run<Benchmarks>();
    }

The results are:


    BenchmarkDotNet=v0.12.0, OS=Windows 10.0.14393.3443 (1607/AnniversaryUpdate/Redstone1)
    Intel Core i5-4460 CPU 3.20GHz (Haswell), 1 CPU, 4 logical and 4 physical cores
    Frequency=3124994 Hz, Resolution=320.0006 ns, Timer=TSC
    .NET Core SDK=3.1.100
      [Host]     : .NET Core 3.1.0 (CoreCLR 4.700.19.56402, CoreFX 4.700.19.56404), X64 RyuJIT
      DefaultJob : .NET Core 3.1.0 (CoreCLR 4.700.19.56402, CoreFX 4.700.19.56404), X64 RyuJIT
    
    
    |    Method | Count |          Mean |       Error |      StdDev |        Median | Ratio | RatioSD |   Gen 0 | Gen 1 | Gen 2 | Allocated |
    |---------- |------ |--------------:|------------:|------------:|--------------:|------:|--------:|--------:|------:|------:|----------:|
    | ToArray() |     0 |      7.357 ns |   0.2096 ns |   0.1960 ns |      7.323 ns |  1.00 |    0.00 |       - |     - |     - |         - |
    |  ToList() |     0 |     13.174 ns |   0.2094 ns |   0.1958 ns |     13.084 ns |  1.79 |    0.05 |  0.0102 |     - |     - |      32 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |     1 |     23.917 ns |   0.4999 ns |   0.4676 ns |     23.954 ns |  1.00 |    0.00 |  0.0229 |     - |     - |      72 B |
    |  ToList() |     1 |     33.867 ns |   0.7350 ns |   0.6876 ns |     34.013 ns |  1.42 |    0.04 |  0.0331 |     - |     - |     104 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |     6 |     28.242 ns |   0.5071 ns |   0.4234 ns |     28.196 ns |  1.00 |    0.00 |  0.0280 |     - |     - |      88 B |
    |  ToList() |     6 |     43.516 ns |   0.9448 ns |   1.1949 ns |     42.896 ns |  1.56 |    0.06 |  0.0382 |     - |     - |     120 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |    10 |     31.636 ns |   0.5408 ns |   0.4516 ns |     31.657 ns |  1.00 |    0.00 |  0.0331 |     - |     - |     104 B |
    |  ToList() |    10 |     53.870 ns |   1.2988 ns |   2.2403 ns |     53.415 ns |  1.77 |    0.07 |  0.0433 |     - |     - |     136 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |    39 |     58.896 ns |   0.9441 ns |   0.8369 ns |     58.548 ns |  1.00 |    0.00 |  0.0713 |     - |     - |     224 B |
    |  ToList() |    39 |    138.054 ns |   2.8185 ns |   3.2458 ns |    138.937 ns |  2.35 |    0.08 |  0.0815 |     - |     - |     256 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |   100 |    119.167 ns |   1.6195 ns |   1.4357 ns |    119.120 ns |  1.00 |    0.00 |  0.1478 |     - |     - |     464 B |
    |  ToList() |   100 |    274.053 ns |   5.1073 ns |   4.7774 ns |    272.242 ns |  2.30 |    0.06 |  0.1578 |     - |     - |     496 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |   666 |    569.920 ns |  11.4496 ns |  11.2450 ns |    571.647 ns |  1.00 |    0.00 |  0.8688 |     - |     - |    2728 B |
    |  ToList() |   666 |  1,621.752 ns |  17.1176 ns |  16.0118 ns |  1,623.566 ns |  2.85 |    0.05 |  0.8793 |     - |     - |    2760 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |  1000 |    796.705 ns |  16.7091 ns |  19.8910 ns |    796.610 ns |  1.00 |    0.00 |  1.2951 |     - |     - |    4064 B |
    |  ToList() |  1000 |  2,453.110 ns |  48.1121 ns |  65.8563 ns |  2,460.190 ns |  3.09 |    0.10 |  1.3046 |     - |     - |    4096 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() |  1337 |  1,057.983 ns |  20.9810 ns |  41.4145 ns |  1,041.028 ns |  1.00 |    0.00 |  1.7223 |     - |     - |    5416 B |
    |  ToList() |  1337 |  3,217.550 ns |  62.3777 ns |  61.2633 ns |  3,203.928 ns |  2.98 |    0.13 |  1.7357 |     - |     - |    5448 B |
    |           |       |               |             |             |               |       |         |         |       |       |           |
    | ToArray() | 10000 |  7,309.844 ns | 160.0343 ns | 141.8662 ns |  7,279.387 ns |  1.00 |    0.00 | 12.6572 |     - |     - |   40064 B |
    |  ToList() | 10000 | 23,858.032 ns | 389.6592 ns | 364.4874 ns | 23,759.001 ns |  3.26 |    0.08 | 12.6343 |     - |     - |   40096 B |
    
    // * Hints *
    Outliers
      Benchmarks.ToArray(): Default -> 2 outliers were removed (35.20 ns, 35.29 ns)
      Benchmarks.ToArray(): Default -> 2 outliers were removed (38.51 ns, 38.88 ns)
      Benchmarks.ToList(): Default  -> 1 outlier  was  removed (64.69 ns)
      Benchmarks.ToArray(): Default -> 1 outlier  was  removed (67.02 ns)
      Benchmarks.ToArray(): Default -> 1 outlier  was  removed (130.08 ns)
      Benchmarks.ToArray(): Default -> 1 outlier  was  detected (541.82 ns)
      Benchmarks.ToArray(): Default -> 1 outlier  was  removed (7.82 us)
    
    // * Legends *
      Count     : Value of the 'Count' parameter
      Mean      : Arithmetic mean of all measurements
      Error     : Half of 99.9% confidence interval
      StdDev    : Standard deviation of all measurements
      Median    : Value separating the higher half of all measurements (50th percentile)
      Ratio     : Mean of the ratio distribution ([Current]/[Baseline])
      RatioSD   : Standard deviation of the ratio distribution ([Current]/[Baseline])
      Gen 0     : GC Generation 0 collects per 1000 operations
      Gen 1     : GC Generation 1 collects per 1000 operations
      Gen 2     : GC Generation 2 collects per 1000 operations
      Allocated : Allocated memory per single operation (managed only, inclusive, 1KB = 1024B)
      1 ns      : 1 Nanosecond (0.000000001 sec)

Lueluebke answered 6/2, 2020 at 21:23 Comment(9)
If you're not planning to mutate the collection, I'd think the intent can better be shown with ToImmutableArray() (from the System.Collections.Immutable package) 😉Ecumenicity
@ArturoTorresSánchez true, but if the collection is not exposed outside of a method, I would just use an array.Lueluebke
Thanks for this. The chosen answer is a mere argument and assuming results following that argument. To do this scientifically and as a bonus know how much of a difference there is, there's only one real way to know.Delivery
Could this test suffer from repeatedly running with the same length of the arrays? That would mean that buffers of the right size are available in LargeArrayBuilderSyncopated
This doesn't take into account that RangeIterator.ToArray and RangeIterator.ToList implementations know the final size of the collection. With any more complex LINQ expressions (e.g. with Where) the size can't be known and the result collection will have to be dynamically resized. So this answer is valid only for a small subset of real-world cases.Redan
@ErikOvegård @Lueluebke @Delivery @Redan I modified the benchmark code to: public IEnumerable<int> Items => Enumerable.Range(0, Count).Where(i => i % 17 == 0); and in most of the cases ToList is around 10% faster, with less allocations.Recurrent
@Lueluebke could you please consider editing your answer, since it is most probably misleading?Recurrent
@AndreiBozantan you can submit edits tooLueluebke
@AndreiBozantan Probably it would be even better to add your own answer, because editing this one with a completely different result would kind of invalidate the upvotes. Once you've done that, edit this answer with a short notice at the top that the results are valid only in certain scenarios, and which ones.Bax
I
77

(seven years later...)

A couple of other (good) answers have concentrated on microscopic performance differences that will occur.

This post is just a supplement to mention the semantic difference that exists between the IEnumerator<T> produced by an array (T[]) as compared to that returned by a List<T>.

Best illustrated with by example:

IList<int> source = Enumerable.Range(1, 10).ToArray();  // try changing to .ToList()

foreach (var x in source)
{
  if (x == 5)
    source[8] *= 100;
  Console.WriteLine(x);
}

The above code will run with no exception and produces the output:

1
2
3
4
5
6
7
8
900
10

This shows that the IEnumarator<int> returned by an int[] does not keep track on whether the array has been modified since the creation of the enumerator.

Note that I declared the local variable source as an IList<int>. In that way I make sure the C# compiler does not optimze the foreach statement into something which is equivalent to a for (var idx = 0; idx < source.Length; idx++) { /* ... */ } loop. This is something the C# compiler might do if I use var source = ...; instead. In my current version of the .NET framework the actual enumerator used here is a non-public reference-type System.SZArrayHelper+SZGenericArrayEnumerator`1[System.Int32] but of course this is an implementation detail.

Now, if I change .ToArray() into .ToList(), I get only:

1
2
3
4
5

followed by a System.InvalidOperationException blow-up saying:

Collection was modified; enumeration operation may not execute.

The underlying enumerator in this case is the public mutable value-type System.Collections.Generic.List`1+Enumerator[System.Int32] (boxed inside an IEnumerator<int> box in this case because I use IList<int>).

In conclusion, the enumerator produced by a List<T> keeps track on whether the list changes during enumeration, while the enumerator produced by T[] does not. So consider this difference when choosing between .ToList() and .ToArray().

People often add one extra .ToArray() or .ToList() to circumvent a collection that keeps track on whether it was modified during the life-time of an enumerator.

(If anybody wants to know how the List<> keeps track on whether collection was modified, there is a private field _version in this class which is changed everytime the List<> is updated. It would in fact be possible to change this behavior of List<> by simply removing the line that increments _version in the set accessor of the indexer public T this[int index], just like it was done inside Dictionary<,> recently, as described in another answer.)

Indenture answered 20/12, 2016 at 16:3 Comment(1)
Very informative, but this is just a difference between array and list, isnt it. This isn't specific to ToArray vs ToList implementation. Not to be critical, but just in case its helpful for others.Kirven
F
29

I agree with @mquander that the performance difference should be insignificant. However, I wanted to benchmark it to be sure, so I did - and it is, insignificant.

Testing with List<T> source:
ToArray time: 1934 ms (0.01934 ms/call), memory used: 4021 bytes/array
ToList  time: 1902 ms (0.01902 ms/call), memory used: 4045 bytes/List

Testing with array source:
ToArray time: 1957 ms (0.01957 ms/call), memory used: 4021 bytes/array
ToList  time: 2022 ms (0.02022 ms/call), memory used: 4045 bytes/List

Each source array/List had 1000 elements. So you can see that both time and memory differences are negligible.

My conclusion: you might as well use ToList(), since a List<T> provides more functionality than an array, unless a few bytes of memory really matter to you.

Farandole answered 11/1, 2011 at 23:10 Comment(6)
I wonder if this result would be different if you used a large struct instead of a primitive type or class.Delegacy
List<T>.ToList ???? What sense ? U'd better try to give an IEnumerable into it, wich doesn't implement ICollection interface.Valaria
I wanted to make sure I'm measuring only the time of the ToList or ToArray call and not the enumeration of any IEnumerable. List<T>.ToList() still creates a new List<T> - it doesn't simply "return this".Farandole
-1 The behaviours of ToArray() and ToList() differ too much when they are supplied with an ICollection<T> parameter - They just do a single allocation and a single copy operation. Both List<T> and Array implement ICollection<T>, so your benchmarks are not valid at all.Seabee
For anyone interested, I posted my own benchmark as a separate answer. It uses .Select(i => i) to avoid the ICollection<T> implementation problem, and includes a control group to see how much of the time is just taken iterating over the source IEnumerable<> in the first place.Chelton
"you might as well use ToList(), since a List<T> provides more functionality than an array, unless a few bytes of memory really matter to you." Sometimes having less functionality is better.Lueluebke
C
23

ToList() is usually preferred if you use it on IEnumerable<T> (from ORM, for instance). If the length of sequence is not known at the beginning, ToArray() creates dynamic-length collection like List and then converts it to array, which takes extra time.

Crude answered 1/2, 2010 at 14:55 Comment(2)
I've decided that readability trumps performance in this case. I now only use ToList when I expect to continue adding elements. In all other cases (most cases), I use ToArray. But thanks for the input!Breadfruit
Looking in ILSpy, Enumerable.ToArray() calls new Buffer<TSource>(source).ToArray(). In the Buffer constructor if the source implement ICollection then it calls source.CopyTo(items, 0), and then .ToArray() returns the internal items array directly. So there is no conversion that takes extra time in that case. If the source doesn't implement ICollection then the ToArray will result in an array copy in order to trim the extra unused locations from the end of the array as described by Scott Rippey's comment above.Asiatic
J
22

The memory will always be allocated twice - or something close to that. As you can not resize an array, both methods will use some sort of mechanism to gather the data in a growing collection. (Well, the List is a growing collection in itself.)

The List uses an array as internal storage, and doubles the capacity when needed. This means that by average 2/3 of the items has been reallocated at least once, half of those reallocated at least twice, half of those at least thrice, and so on. That means that each item has by average been reallocated 1.3 times, which is not very much overhead.

Remember also that if you are collecting strings, the collection itself only contains the references to the strings, the strings themselves aren't reallocated.

Judgment answered 9/7, 2009 at 19:57 Comment(3)
This may be an ignorant thing to ask, but doesn't the 2/3, 1/3, 1/6 logic you outline assume that the List's array can be extended in place? That is, there's free space at the end of the array so that the existing allocation need not be moved?Initiate
@JonofAllTrades: No, the array is never extended in place, the memory management in .NET simply doesn't do that. If it would be extended in place, there would be no need for reallocation of the items.Judgment
Ah, I see: the items which are not reallocated did not have to do so because they were in the final allocation. All of the items allocated in previous allocations are moved, but due to the logarithmic increases in array length this is a calculable fraction. Thanks for clarifying!Initiate
C
21

I found the other benchmarks people have done here lacking, so here's my crack at it. Let me know if you find something wrong with my methodology.

/* This is a benchmarking template I use in LINQPad when I want to do a
 * quick performance test. Just give it a couple of actions to test and
 * it will give you a pretty good idea of how long they take compared
 * to one another. It's not perfect: You can expect a 3% error margin
 * under ideal circumstances. But if you're not going to improve
 * performance by more than 3%, you probably don't care anyway.*/
void Main()
{
    // Enter setup code here
    var values = Enumerable.Range(1, 100000)
        .Select(i => i.ToString())
        .ToArray()
        .Select(i => i);
    values.GetType().Dump();
    var actions = new[]
    {
        new TimedAction("ToList", () =>
        {
            values.ToList();
        }),
        new TimedAction("ToArray", () =>
        {
            values.ToArray();
        }),
        new TimedAction("Control", () =>
        {
            foreach (var element in values)
            {
                // do nothing
            }
        }),
        // Add tests as desired
    };
    const int TimesToRun = 1000; // Tweak this as necessary
    TimeActions(TimesToRun, actions);
}


#region timer helper methods
// Define other methods and classes here
public void TimeActions(int iterations, params TimedAction[] actions)
{
    Stopwatch s = new Stopwatch();
    int length = actions.Length;
    var results = new ActionResult[actions.Length];
    // Perform the actions in their initial order.
    for (int i = 0; i < length; i++)
    {
        var action = actions[i];
        var result = results[i] = new ActionResult { Message = action.Message };
        // Do a dry run to get things ramped up/cached
        result.DryRun1 = s.Time(action.Action, 10);
        result.FullRun1 = s.Time(action.Action, iterations);
    }
    // Perform the actions in reverse order.
    for (int i = length - 1; i >= 0; i--)
    {
        var action = actions[i];
        var result = results[i];
        // Do a dry run to get things ramped up/cached
        result.DryRun2 = s.Time(action.Action, 10);
        result.FullRun2 = s.Time(action.Action, iterations);
    }
    results.Dump();
}

public class ActionResult
{
    public string Message { get; set; }
    public double DryRun1 { get; set; }
    public double DryRun2 { get; set; }
    public double FullRun1 { get; set; }
    public double FullRun2 { get; set; }
}

public class TimedAction
{
    public TimedAction(string message, Action action)
    {
        Message = message;
        Action = action;
    }
    public string Message { get; private set; }
    public Action Action { get; private set; }
}

public static class StopwatchExtensions
{
    public static double Time(this Stopwatch sw, Action action, int iterations)
    {
        sw.Restart();
        for (int i = 0; i < iterations; i++)
        {
            action();
        }
        sw.Stop();

        return sw.Elapsed.TotalMilliseconds;
    }
}
#endregion

You can download the LINQPad Script here.

Results: ToArray vs ToList performance

Tweaking the code above, you will discover that:

  1. The difference is less significant when dealing with smaller arrays. More iterations, but smaller arrays
  2. The difference is less significant when dealing with ints rather than strings.
  3. Using large structs instead of strings takes a lot more time generally, but doesn't really change the ratio much.

This agrees with the conclusions of the top-voted answers:

  1. You're unlikely to notice a performance difference unless your code is frequently producing many large lists of data. (There was only a 200ms difference when creating 1000 lists of 100K strings apiece.)
  2. ToList() consistently runs faster, and would be a better choice if you're not planning to hang on to the results for a long time.

Update

@JonHanna pointed out that depending on the implementation of Select it's possible for a ToList() or ToArray() implementation to predict the resulting collection's size ahead of time. Replacing .Select(i => i) in the code above with Where(i => true) yields very similar results at the moment, and is more likely to do so regardless of the .NET implementation.

Benchmark using Where instead of Select

Update 2024

.NET has come a long way since I last visited this answer, and things have shifted somewhat. Here are the results of the test in my previous Update, running in .NET 7.

Unoptimized/Debug: Unoptimized 2024 Optimized/Release: Optimized 2024

As you can see, ToArray() is now slightly faster than ToList(). This reinforces the dangers of premature optimization: you could spend all your time optimizing for how things are currently, only to miss out on optimizations that happen in future versions of the framework.

Chelton answered 8/9, 2017 at 19:16 Comment(5)
In .NET Core both cases should be better here than on netfx, because it'll realise the size is going to be 100000 and use that to optimise both ToList() and ToArray(), with ToArray() being very slightly lighter because it doesn't need the shrink operation it would need otherwise, which is the one place ToList() has the advantage. The example in the question would still lose out, because the Where means such size prediction can't be done.Topography
@JonHanna: Thanks for the quick feedback. I didn't know .NET Core was making that optimization. That's cool. In my code, .Select(i => i) could be replaced with .Where(i => true) to correct for that.Chelton
Yes, that'd stop the optimisation affecting it on corefx. It might be interesting to have both a size that's a power of two (which should give ToArray() an advantage) and one that isn't, as above, and compare the results.Topography
@JonHanna: Interestingly, ToArray() still loses in the best-case scenario. With Math.Pow(2, 15) elements, it's (ToList: 700ms, ToArray: 900ms). Adding one more element bumps it to (ToList: 925, ToArray: 1350). I wonder if ToArray is still copying the array even when it's already the perfect size? They probably figured it was a rare enough occurrence that it wasn't worth the extra conditional.Chelton
It didn't copy on exact size match, even before we started optimising it in corefx, so it's the case where it gets the most breaks.Topography
D
17

I know this is an old post, but after having the same question and doing some research, I have found something interesting that might be worth sharing.

First, I agree with @mquander and his answer. Performance-wise the two are identical.

However, I have been using Reflector to take a look at the methods in the System.Linq.Enumerable extensions namespace, and I have noticed a very common optimization.
Whenever possible, the IEnumerable<T> source is cast to IList<T> or ICollection<T> to optimize the method. For example, look at ElementAt(int).

Interestingly, Microsoft chose to only optimize for IList<T>, but not IList. It looks like Microsoft prefers to use the IList<T> interface.

Delegacy answered 12/7, 2010 at 19:55 Comment(3)
I did a test and found out something surprising. An array DOES implement IList<T>! Using Reflector to analyze System.Array only reveals an inheritance chain of IList, ICollection, IEnumerable but using run-time reflection I found out that string[] has an inheritance chain of IList, ICollection, IEnumerable, IList<string>, ICollection<string>, IEnumerable<string>. Therefore, I don't have a better answer than @mquander!Delegacy
@ScottRippey Yes. The odd observation you noticed is actually part of a "hack" - and it has some rather weird implications too regarding "fixed-size" and similar properties (with some inconsistencies depending on how you cast it). There are some fairly big comments touching this subject inside the .net source-code. Sorry for not linking but if I remember correctly it's quite easy to find (inside the array-class). (And there is also a big SO question discussing the inconsistencies.... somewhere... >__>)Lucylud
@ScottRippey just FYI I found this answer which has to do with your comment: https://mcmap.net/q/65298/-what-interfaces-do-all-arrays-implement-in-cTanatanach
K
15

You should base your decision to go for ToList or ToArray based on what ideally the design choice is. If you want a collection that can only be iterated and accessed by index, choose ToArray. If you want additional capabilities of adding and removing from the collection later on without much hassle, then do a ToList (not really that you cant add to an array, but that's not the right tool for it usually).

If performance matters, you should also consider what would be faster to operate on. Realistically, you wont call ToList or ToArray a million times, but might work on the obtained collection a million times. In that respect [] is better, since List<> is [] with some overhead. See this thread for some efficiency comparison: Which one is more efficient : List<int> or int[]

In my own tests a while ago, I had found ToArray faster. And I'm not sure how skewed the tests were. The performance difference is so insignificant though, which can noticeable only if you are running these queries in a loop millions of times.

Kirven answered 7/12, 2012 at 10:42 Comment(1)
Yes - if the compiler knows that you are iterating over an array (rather than an IEnumerable<>), it can optimize the iteration significantly.Milwaukee
B
12

A very late answer but I think it will be helpful for googlers.

They both suck when they created using linq. They both implement same code to resize buffer if necessary. ToArray internally uses a class to convert IEnumerable<> to array, by allocating an array of 4 elements. If that is not enough than it doubles the size by creating a new array double the size of current and copying current array to it. At the end it allocates a new array of count of your items. If your query returns 129 elements then ToArray will make 6 allocations and memory copy operations to create a 256 element array and than am another array of 129 to return. so much for memory efficiency.

ToList does the same thing, but it skips the last allocation since you can add items in the future. List does not care if it is created from a linq query or created manually.

for creation List is better with memory but worse with cpu since list is a generic solution every action requires range checks additional to the .net's internal range checks for arrays.

So if you will iterate through your result set too many times, then arrays are good since it means less range checks than lists, and compilers generally optimizes arrays for sequential access.

List's initialization allocation can be better if you specify capacity parameter when you create it. In this case it will allocate array only once, assuming you know the result size. ToList of linq does not specify an overload to provide it, so we have to create our extension method that creates a list with given capacity and then uses List<>.AddRange.

To finish this answer I have to write following sentences

  1. At the end, you can use either an ToArray, or ToList, performance will not be so different ( see answer of @EMP ).
  2. You are using C#. If you need performance then do not worry about writing about high performance code, but worry about not writing bad performance code.
  3. Always target x64 for high performance code. AFAIK, x64 JIT is based on C++ compiler, and does some funny things like tail recursion optimizations.
  4. With 4.5 you can also enjoy the profile guided optimization and multi core JIT.
  5. At last, you can use async/await pattern to process it quicker.
Brod answered 8/10, 2013 at 15:11 Comment(7)
They both suck? Do you have an alternate idea that doesn't require redundant memory allocation?Kirven
In the context of question, yes, they both suck but because of redundant allocations, and nothing else. To reduce redundant allocation one can use linked lists at the expense of memory and iteration speed. At the end of the day, this is what we do, we make trade offs. Another idea if to create a list with a capacity of 200 (for example) and then load items. This will also reduce redundancy, but arrays are always faster, so this is another trade off.Brod
Create a list of 200? That might avoid resizing, but I was talking about redundant memory used. You cannot help it because there is no pre knowledge about what the size could be. You can already specify the capacity in the constructor of a List<T>, but when you don't or when you can't, you can't help it.Kirven
the only redundant data in memory is the contents of the array which is a list of pointers (in this case). one million 64 bit pointers takes as much as 8 MB of memory, which is nothing compared to one million objects they point to. 200 is just a number, and it has a chance to reduce number of resize calls a maximum of 5 times. and yes, we can't help it. we don't have better options. I don't have a better solution, but this doesn't mean I am not allowed to say where the problem is.Brod
hmm in the end it is where you draw the line. I like the current implementation. The tone of your answer made me think it was criticism rather than where the problem is :)Kirven
+1 for properly noting that pre-allocation and an extension method can drastically reduce allocation costs (and GC churn) and yes, nawfal, it does require some knowledge of a system to optimize in this fashion, but most of us who need to squeeze out every cpu cycle we can are already intimately aware of our allocation models (moreso than the staged allocations of the framework.) this is an excellent detail of behavior as well, less misleading that the elected answer and more accurate in either case.Lawful
Doubling the list size when expanding it makes Add be O(1) amortised time. What did you think it should do?Loup
G
6

This is an old question - but for the benefit of users who stumble upon it, there is also an alternative of 'Memoizing' the Enumerable - which has the effect of caching and stopping multiple enumeration of a Linq statement, which is what ToArray() and ToList() are used for a lot, even though the collection attributes of the list or array are never used.

Memoize is available in the RX/System.Interactive lib, and is explained here: More LINQ with System.Interactive

(From Bart De'Smet's blog which is a highly recommended read if you are working with Linq to Objects a lot)

Greysun answered 14/11, 2011 at 10:40 Comment(0)
L
6

One option is to add your own extension method that returns a readonly ICollection<T>. This can be better than using ToList or ToArray when you do not want to use either the indexing properties of an array/list, or add/remove from a list.

public static class EnumerableExtension
{
    /// <summary>
    /// Causes immediate evaluation of the linq but only if required.
    /// As it returns a readonly ICollection, is better than using ToList or ToArray
    /// when you do not want to use the indexing properties of an IList, or add to the collection.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="enumerable"></param>
    /// <returns>Readonly collection</returns>
    public static ICollection<T> Evaluate<T>(this IEnumerable<T> enumerable)
    {
        //if it's already a readonly collection, use it
        var collection = enumerable as ICollection<T>;
        if ((collection != null) && collection.IsReadOnly)
        {
            return collection;
        }
        //or make a new collection
        return enumerable.ToList().AsReadOnly();
    }
}

Unit tests:

[TestClass]
public sealed class EvaluateLinqTests
{
    [TestMethod]
    public void EvalTest()
    {
        var list = new List<int> {1, 2, 3};
        var linqResult = list.Select(i => i);
        var linqResultEvaluated = list.Select(i => i).Evaluate();
        list.Clear();
        Assert.AreEqual(0, linqResult.Count());
        //even though we have cleared the underlying list, the evaluated list does not change
        Assert.AreEqual(3, linqResultEvaluated.Count());
    }

    [TestMethod]
    public void DoesNotSaveCreatingListWhenHasListTest()
    {
        var list = new List<int> {1, 2, 3};
        var linqResultEvaluated = list.Evaluate();
        //list is not readonly, so we expect a new list
        Assert.AreNotSame(list, linqResultEvaluated);
    }

    [TestMethod]
    public void SavesCreatingListWhenHasReadonlyListTest()
    {
        var list = new List<int> {1, 2, 3}.AsReadOnly();
        var linqResultEvaluated = list.Evaluate();
        //list is readonly, so we don't expect a new list
        Assert.AreSame(list, linqResultEvaluated);
    }

    [TestMethod]
    public void SavesCreatingListWhenHasArrayTest()
    {
        var list = new[] {1, 2, 3};
        var linqResultEvaluated = list.Evaluate();
        //arrays are readonly (wrt ICollection<T> interface), so we don't expect a new object
        Assert.AreSame(list, linqResultEvaluated);
    }

    [TestMethod]
    [ExpectedException(typeof (NotSupportedException))]
    public void CantAddToResultTest()
    {
        var list = new List<int> {1, 2, 3};
        var linqResultEvaluated = list.Evaluate();
        Assert.AreNotSame(list, linqResultEvaluated);
        linqResultEvaluated.Add(4);
    }

    [TestMethod]
    [ExpectedException(typeof (NotSupportedException))]
    public void CantRemoveFromResultTest()
    {
        var list = new List<int> {1, 2, 3};
        var linqResultEvaluated = list.Evaluate();
        Assert.AreNotSame(list, linqResultEvaluated);
        linqResultEvaluated.Remove(1);
    }
}
Ligate answered 28/11, 2012 at 9:37 Comment(4)
It is worth noting that the read-only collection contract only stipulates that the user of the object may not modify it, but the owner may still do so if it keeps a reference to it that offers a mutable interface. For interfaces that guarantee that the underlying structure will never change, look at immutable collections. As to why immutable, or read-only, or plain read-write collections are better or worse, one needs a reference point for comparison; there is no ultimate answer (else we wouldn't have to choose).Hammons
@Hammons Note I do Tolist before AsReadOnly, so there are no references to the underlying mutable.Ligate
You're entirely right, and that was probably the best way to do things before immutable collections came to the BCL (I see the first beta came out a month after your answer).Hammons
Immutable collections exist for thread safety, where threads can assume that it won't change, and if it does, a new version is created, instead of racing against readers and changing it while they use it. This way, nobody ever needs to acquire a lock.Loup
E
5

Old question but new questioners at all time.

According to source of System.Linq.Enumerable, ToList just return a new List(source), while ToArray use a new Buffer<T>(source).ToArray() to return a T[].

About memory allocation:

While running on an IEnumerable<T> only object, ToArray do allocate memory one more time than ToList. But you do not have to care about it in most cases, because GC will do the garbage collection when needed.

About the runtime efficient:

Those who are questioning this question can run the following code on your own machine, and you'll get your answer.

class PersonC
{
    public Guid uuid;
    public string name;
    public int age;
    public bool sex;
    public DateTime BirthDay;
    public double weight;
}

struct PersonS
{
    public Guid uuid;
    public string name;
    public int age;
    public bool sex;
    public DateTime BirthDay;
    public double weight;
}

class PersonT<T> : IEnumerable<T>
{
    private List<T> items;
    public PersonT(IEnumerable<T> init)
    {
        items = new List<T>(init);
    }

    public IEnumerator<T> GetEnumerator() => items.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => items.GetEnumerator();
}

private IEnumerable<PersonC> C(int count)
{
    for (var i = 0; i < count; ++i)
    {
        var guid = Guid.NewGuid();
        var guidBytes = guid.ToByteArray(); //16 bytes
        yield return new PersonC
        {
            uuid = guid,
            name = guid.ToString(),
            age = guidBytes[0] ^ guidBytes[7],
            sex = guidBytes[14] % 2 == 0,
            BirthDay = DateTime.Now.AddDays(-guidBytes[11] * 18),
            weight = guidBytes[12] * 100
        };
    }
}

private IEnumerable<PersonS> S(int count)
{
    for (var i = 0; i < count; ++i)
    {
        var guid = Guid.NewGuid();
        var guidBytes = guid.ToByteArray(); //16 bytes
        yield return new PersonS
        {
            uuid = guid,
            name = guid.ToString(),
            age = guidBytes[0] ^ guidBytes[7],
            sex = guidBytes[14] % 2 == 0,
            BirthDay = DateTime.Now.AddDays(-guidBytes[11] * 18),
            weight = guidBytes[12] * 100
        };
    }
}

private void MakeLog(string test, List<long> log) =>
    Console.WriteLine("{0} {1} ms -> [{2}]",
        test,
        log.Average(),
        string.Join(", ", log)
    );

private void Test1(int times, int count)
{
    var test = Enumerable.Range(1, times).ToArray();

    MakeLog("C.ToList", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = C(count).ToList();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("C.ToArray", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = C(count).ToArray();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("S.ToList", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = S(count).ToList();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("S.ToArray", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = S(count).ToArray();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());
}

private void Test2(int times, int count)
{
    var test = Enumerable.Range(1, times).ToArray();

    var dataC1 = new PersonT<PersonC>(C(count));
    var dataS1 = new PersonT<PersonS>(S(count));

    MakeLog("C1.ToList", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataC1.ToList();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("C1.ToArray", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataC1.ToArray();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("S1.ToList", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataS1.ToList();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("S1.ToArray", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataS1.ToArray();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());
}

private void Test3(int times, int count)
{
    var test = Enumerable.Range(1, times).ToArray();

    var dataC2 = (ICollection<PersonC>) new List<PersonC>(C(count));
    var dataS2 = (ICollection<PersonS>) new List<PersonS>(S(count));

    MakeLog("C2.ToList", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataC2.ToList();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("C2.ToArray", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataC2.ToArray();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("S2.ToList", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataS2.ToList();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());

    MakeLog("S2.ToArray", test.Select(o =>
    {
        var sw = new Stopwatch();
        GC.Collect();
        sw.Start();
        var ret = dataS2.ToArray();
        sw.Stop();
        return sw.ElapsedMilliseconds;
    }).ToList());
}

private void TestMain()
{
    const int times = 100;
    const int count = 1_000_000 + 1;
    Test1(times, count);
    Test2(times, count);
    Test3(times, count);
}

I got these results on my machine:

Group1:

C.ToList 761.79 ms -> [775, 755, 759, 759, 756, 759, 765, 750, 757, 762, 759, 754, 757, 753, 763, 753, 759, 756, 768, 754, 763, 757, 757, 777, 780, 758, 754, 758, 762, 754, 758, 757, 763, 758, 760, 754, 761, 755, 764, 847, 952, 755, 747, 763, 760, 758, 754, 763, 761, 758, 750, 764, 757, 763, 762, 756, 753, 759, 759, 757, 758, 779, 765, 760, 760, 756, 760, 756, 755, 764, 759, 753, 757, 760, 752, 764, 758, 760, 758, 760, 755, 761, 751, 753, 761, 762, 761, 758, 759, 752, 765, 756, 760, 755, 757, 753, 760, 751, 755, 779]
C.ToArray 782.56 ms -> [783, 774, 771, 771, 773, 774, 775, 775, 772, 770, 771, 774, 771, 1023, 975, 772, 767, 776, 771, 779, 772, 779, 775, 771, 775, 773, 775, 771, 765, 774, 770, 781, 772, 771, 781, 762, 817, 770, 775, 779, 769, 774, 763, 775, 777, 769, 777, 772, 775, 778, 775, 771, 770, 774, 772, 769, 772, 769, 774, 775, 768, 775, 769, 774, 771, 776, 774, 773, 778, 769, 778, 767, 770, 787, 783, 779, 771, 768, 805, 780, 779, 767, 773, 771, 773, 785, 1044, 853, 775, 774, 775, 771, 770, 769, 770, 776, 770, 780, 821, 770]
S.ToList 704.2 ms -> [687, 702, 709, 691, 694, 710, 696, 698, 700, 694, 701, 719, 706, 694, 702, 699, 699, 703, 704, 701, 703, 705, 697, 707, 691, 697, 707, 692, 721, 698, 695, 700, 704, 700, 701, 710, 700, 705, 697, 711, 694, 700, 695, 698, 701, 692, 696, 702, 690, 699, 708, 700, 703, 714, 701, 697, 700, 699, 694, 701, 697, 696, 699, 694, 709, 1068, 690, 706, 699, 699, 695, 708, 695, 704, 704, 700, 695, 704, 695, 696, 702, 700, 710, 708, 693, 697, 702, 694, 700, 706, 699, 695, 706, 714, 704, 700, 695, 697, 707, 704]
S.ToArray 742.5 ms -> [742, 743, 733, 745, 741, 724, 738, 745, 728, 732, 740, 727, 739, 740, 726, 744, 758, 732, 744, 745, 730, 739, 738, 723, 745, 757, 729, 741, 736, 724, 744, 756, 739, 766, 737, 725, 741, 742, 736, 748, 742, 721, 746, 1043, 806, 747, 731, 727, 742, 742, 726, 738, 746, 727, 739, 743, 730, 744, 753, 741, 739, 746, 728, 740, 744, 734, 734, 738, 731, 747, 736, 731, 765, 735, 726, 740, 743, 730, 746, 742, 725, 731, 757, 734, 738, 741, 732, 747, 744, 721, 742, 741, 727, 745, 740, 730, 747, 760, 737, 740]

C1.ToList 32.34 ms -> [35, 31, 31, 31, 32, 31, 31, 31, 31, 31, 31, 31, 31, 31, 33, 32, 31, 31, 31, 31, 30, 32, 31, 31, 31, 31, 32, 30, 31, 31, 31, 30, 32, 31, 31, 31, 36, 31, 31, 31, 32, 30, 31, 32, 31, 31, 31, 31, 31, 32, 31, 31, 31, 31, 33, 32, 31, 32, 31, 31, 33, 31, 31, 31, 31, 31, 32, 31, 32, 31, 34, 38, 68, 42, 79, 33, 31, 31, 31, 31, 31, 30, 30, 30, 30, 31, 31, 31, 31, 32, 31, 32, 31, 31, 31, 32, 33, 33, 31, 31]
C1.ToArray 56.32 ms -> [57, 56, 59, 54, 54, 55, 56, 57, 54, 54, 55, 55, 57, 56, 59, 57, 56, 58, 56, 56, 54, 56, 57, 55, 55, 55, 57, 58, 57, 58, 55, 55, 56, 55, 57, 56, 56, 59, 56, 56, 56, 56, 58, 56, 57, 56, 56, 57, 56, 55, 56, 56, 56, 59, 56, 56, 56, 55, 55, 54, 55, 54, 57, 56, 56, 56, 55, 55, 56, 56, 56, 59, 56, 56, 57, 56, 57, 56, 56, 56, 56, 62, 55, 56, 56, 56, 69, 57, 58, 56, 57, 58, 56, 57, 56, 56, 56, 56, 56, 56]
S1.ToList 88.69 ms -> [96, 90, 90, 89, 91, 88, 89, 90, 96, 89, 89, 89, 90, 90, 90, 89, 90, 90, 89, 90, 89, 91, 89, 91, 89, 91, 89, 90, 90, 89, 87, 88, 87, 88, 87, 87, 87, 87, 88, 88, 87, 87, 89, 87, 87, 87, 91, 88, 87, 86, 89, 87, 90, 89, 89, 90, 89, 87, 87, 87, 86, 87, 88, 90, 88, 87, 87, 92, 87, 87, 88, 88, 88, 86, 86, 87, 88, 87, 87, 87, 89, 87, 89, 87, 90, 89, 89, 89, 91, 89, 90, 89, 90, 88, 90, 90, 90, 88, 89, 89]
S1.ToArray 143.26 ms -> [130, 129, 130, 131, 133, 130, 131, 130, 135, 137, 130, 136, 132, 131, 130, 131, 132, 130, 132, 136, 130, 131, 157, 153, 194, 364, 176, 189, 203, 194, 189, 192, 183, 140, 142, 147, 145, 134, 159, 158, 142, 167, 130, 143, 145, 144, 160, 154, 156, 153, 153, 164, 142, 145, 137, 134, 145, 143, 142, 135, 133, 133, 135, 134, 134, 139, 139, 133, 134, 141, 133, 132, 133, 132, 133, 131, 135, 132, 133, 132, 128, 128, 130, 132, 129, 129, 129, 129, 129, 128, 134, 129, 129, 129, 129, 128, 128, 137, 130, 131]

C2.ToList 3.25 ms -> [5, 3, 3, 3, 3, 4, 3, 4, 3, 4, 3, 3, 3, 4, 4, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 4, 3, 4, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 4, 3, 3, 3, 3, 3, 4, 3, 4, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 4, 3, 3, 3, 4, 3, 3, 4, 3, 3, 3, 4, 3, 3, 3, 3, 3]
C2.ToArray 3.37 ms -> [4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 5, 4, 9, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 4, 4, 3, 3, 4, 4, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 4, 4, 3, 4, 4, 3, 3, 4, 3, 3, 4, 3, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 4, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 4, 3, 4, 3, 3, 3]
S2.ToList 37.72 ms -> [38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 40, 38, 38, 39, 39, 38, 38, 38, 38, 37, 37, 37, 37, 39, 37, 37, 39, 38, 37, 37, 37, 37, 39, 38, 37, 37, 38, 37, 38, 37, 37, 38, 37, 37, 37, 38, 37, 37, 36, 37, 38, 37, 39, 37, 39, 38, 37, 38, 38, 38, 38, 38, 38, 37, 38, 38, 38, 38, 38, 37, 38, 37, 37, 38, 37, 37, 39, 41, 37, 38, 38, 37, 37, 37, 37, 38, 37, 37, 37, 40, 37, 37, 37, 37, 39, 38]
S2.ToArray 38.86 ms -> [39, 37, 39, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 39, 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 38, 38, 38, 39, 37, 38, 38, 38, 38, 38, 37, 37, 38, 37, 37, 38, 38, 40, 38, 38, 38, 38, 38, 39, 38, 38, 39, 38, 38, 39, 38, 38, 40, 38, 39, 38, 38, 39, 38, 38, 38, 38, 38, 39, 38, 38, 38, 39, 39, 37, 38, 38, 39, 71, 78, 37, 37, 37, 39, 38, 38, 39, 38, 38, 38, 38, 38, 39, 38, 38, 38, 39, 38, 38, 38]

Group2:

C.ToList 756.81 ms
C.ToArray 774.21 ms
S.ToList 709.7 ms
S.ToArray 753.51 ms

C1.ToList 32.06 ms
C1.ToArray 56.58 ms
S1.ToList 89.43 ms
S1.ToArray 132.85 ms

C2.ToList 3.45 ms
C2.ToArray 3.36 ms
S2.ToList 41.43 ms
S2.ToArray 40.84 ms

Group3:

C.ToList 756.64 ms
C.ToArray 771.56 ms
S.ToList 705.42 ms
S.ToArray 749.59 ms

C1.ToList 31.45 ms
C1.ToArray 57.03 ms
S1.ToList 91.26 ms
S1.ToArray 129.77 ms

C2.ToList 3.26 ms
C2.ToArray 3.29 ms
S2.ToList 41.57 ms
S2.ToArray 40.69 ms

Group4:

C.ToList 729.65 ms -> [749, 730, 721, 719, 723, 743, 721, 724, 727, 722, 716, 725, 723, 726, 718, 722, 731, 722, 723, 725, 723, 722, 728, 726, 728, 718, 726, 1088, 788, 737, 729, 710, 730, 728, 717, 723, 728, 721, 722, 728, 722, 736, 723, 729, 732, 724, 726, 727, 728, 728, 726, 726, 725, 727, 725, 728, 728, 718, 724, 725, 726, 724, 726, 729, 727, 722, 722, 725, 725, 728, 724, 727, 738, 717, 726, 723, 725, 725, 727, 724, 720, 726, 726, 723, 727, 730, 723, 721, 725, 727, 727, 733, 720, 722, 722, 725, 722, 725, 728, 726]
C.ToArray 788.36 ms -> [748, 740, 742, 797, 1090, 774, 781, 787, 784, 786, 786, 782, 781, 781, 784, 783, 783, 781, 783, 787, 783, 784, 775, 789, 784, 785, 778, 774, 781, 783, 786, 781, 780, 788, 778, 785, 777, 781, 786, 782, 781, 787, 782, 787, 784, 773, 783, 782, 781, 777, 783, 781, 785, 788, 777, 776, 784, 784, 783, 789, 778, 781, 791, 768, 779, 783, 781, 787, 786, 781, 784, 781, 785, 781, 780, 809, 1155, 780, 790, 789, 783, 776, 785, 783, 786, 787, 782, 782, 787, 777, 779, 784, 783, 776, 786, 775, 782, 779, 784, 784]
S.ToList 705.54 ms -> [690, 705, 709, 708, 702, 707, 703, 696, 703, 702, 700, 703, 700, 707, 705, 699, 697, 703, 695, 698, 707, 697, 711, 710, 699, 700, 708, 707, 693, 710, 704, 691, 702, 700, 703, 700, 705, 700, 703, 695, 709, 705, 698, 699, 709, 700, 699, 704, 691, 705, 703, 700, 708, 1048, 710, 706, 706, 692, 702, 705, 695, 701, 710, 697, 698, 706, 705, 707, 707, 695, 698, 704, 698, 699, 705, 698, 703, 702, 701, 697, 702, 702, 704, 703, 699, 707, 703, 705, 701, 717, 698, 695, 713, 696, 708, 705, 697, 699, 700, 698]
S.ToArray 745.01 ms -> [751, 743, 727, 734, 736, 745, 739, 750, 739, 750, 758, 739, 744, 738, 730, 744, 745, 739, 744, 750, 733, 735, 743, 731, 749, 748, 727, 746, 749, 731, 737, 803, 1059, 756, 769, 748, 740, 745, 741, 746, 749, 732, 741, 742, 732, 744, 746, 737, 742, 739, 733, 744, 741, 729, 746, 760, 725, 741, 764, 739, 750, 751, 727, 745, 738, 727, 735, 741, 720, 736, 740, 733, 741, 746, 731, 749, 756, 740, 738, 736, 732, 741, 741, 733, 741, 744, 736, 742, 742, 735, 743, 746, 729, 748, 765, 743, 734, 742, 728, 749]

C1.ToList 32.27 ms -> [36, 31, 31, 32, 31, 32, 31, 30, 32, 30, 30, 30, 34, 32, 31, 31, 31, 31, 31, 31, 31, 32, 38, 51, 68, 57, 35, 30, 31, 31, 30, 30, 33, 30, 31, 34, 31, 34, 32, 31, 31, 31, 31, 32, 30, 30, 31, 30, 31, 31, 32, 31, 31, 31, 32, 31, 31, 31, 32, 31, 33, 31, 31, 32, 30, 30, 30, 30, 30, 33, 30, 33, 32, 31, 30, 31, 31, 32, 32, 31, 35, 31, 34, 31, 31, 32, 31, 31, 32, 31, 32, 31, 31, 35, 31, 31, 31, 31, 31, 32]
C1.ToArray 56.72 ms -> [58, 56, 57, 57, 59, 58, 58, 57, 56, 59, 57, 55, 55, 54, 56, 55, 56, 56, 57, 59, 56, 55, 58, 56, 55, 55, 55, 55, 58, 58, 55, 57, 57, 56, 57, 57, 57, 57, 59, 59, 56, 57, 56, 57, 57, 56, 57, 59, 58, 56, 57, 57, 57, 58, 56, 56, 59, 56, 59, 57, 57, 57, 57, 59, 57, 56, 57, 56, 58, 56, 57, 56, 57, 59, 55, 58, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 56, 56, 57, 56, 56, 57, 58, 57, 57, 57, 57, 57]
S1.ToList 90.72 ms -> [95, 90, 90, 89, 89, 89, 91, 89, 89, 87, 91, 89, 89, 89, 91, 89, 89, 89, 90, 89, 89, 90, 88, 89, 88, 90, 89, 90, 89, 89, 90, 90, 89, 89, 90, 91, 89, 91, 89, 90, 89, 89, 90, 91, 89, 89, 89, 89, 89, 89, 90, 89, 89, 89, 90, 89, 90, 89, 91, 89, 90, 89, 90, 89, 90, 89, 96, 89, 90, 89, 89, 89, 89, 89, 90, 89, 89, 89, 90, 87, 89, 90, 90, 91, 89, 91, 89, 89, 90, 91, 90, 89, 93, 144, 149, 90, 90, 89, 89, 89]
S1.ToArray 131.4 ms -> [130, 128, 127, 134, 129, 129, 130, 136, 131, 130, 132, 132, 133, 131, 132, 131, 133, 132, 130, 131, 132, 131, 130, 133, 133, 130, 130, 131, 131, 131, 132, 134, 131, 131, 132, 131, 132, 131, 134, 131, 131, 130, 131, 131, 130, 132, 129, 131, 131, 131, 132, 131, 133, 134, 131, 131, 132, 132, 131, 133, 131, 131, 130, 133, 131, 130, 134, 132, 131, 132, 132, 131, 131, 134, 131, 131, 132, 132, 131, 130, 138, 130, 130, 131, 132, 132, 130, 134, 131, 131, 132, 131, 130, 132, 133, 131, 131, 131, 130, 131]

C2.ToList 3.21 ms -> [4, 3, 3, 3, 4, 3, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 4, 3, 4, 3, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 4, 3, 3, 3]
C2.ToArray 3.22 ms -> [4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 3, 3, 4, 3, 4, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 4, 3, 4, 3, 3, 3, 3, 3, 4, 3, 3, 3, 4, 3, 4, 3, 3, 3, 3, 4]
S2.ToList 41.46 ms -> [42, 40, 41, 40, 42, 40, 40, 40, 40, 40, 40, 40, 40, 41, 40, 40, 41, 40, 40, 40, 39, 41, 41, 39, 40, 40, 43, 40, 39, 40, 40, 40, 40, 40, 40, 41, 40, 40, 40, 43, 40, 43, 75, 76, 47, 39, 40, 40, 40, 40, 42, 40, 41, 40, 40, 40, 44, 41, 40, 42, 42, 40, 41, 41, 41, 41, 41, 40, 41, 41, 41, 41, 42, 41, 40, 41, 41, 42, 42, 41, 40, 41, 41, 41, 41, 41, 40, 42, 40, 42, 41, 41, 41, 43, 41, 41, 41, 41, 42, 41]
S2.ToArray 41.14 ms -> [42, 41, 41, 40, 40, 40, 40, 41, 41, 42, 41, 42, 41, 41, 41, 42, 41, 41, 42, 41, 41, 41, 41, 41, 42, 40, 41, 40, 42, 40, 42, 41, 40, 42, 41, 41, 43, 42, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 40, 40, 41, 41, 41, 40, 42, 41, 41, 41, 41, 41, 40, 41, 41, 42, 41, 41, 41, 42, 41, 41, 41, 41, 41, 41, 42, 42, 42, 41, 45, 46, 41, 40, 41, 41, 42, 41, 41, 41, 41, 41, 41, 40, 41, 43, 40, 40, 40, 40, 43, 41]

Group5:

C.ToList 757.06 ms -> [770, 752, 752, 751, 778, 763, 761, 763, 747, 758, 748, 747, 754, 749, 752, 753, 756, 762, 750, 753, 756, 749, 755, 757, 755, 756, 755, 744, 753, 758, 747, 751, 759, 751, 761, 755, 746, 752, 752, 749, 746, 752, 753, 755, 752, 755, 754, 754, 966, 937, 749, 759, 748, 747, 754, 749, 755, 750, 746, 754, 757, 752, 753, 745, 758, 755, 761, 753, 751, 755, 755, 752, 746, 756, 755, 746, 742, 751, 751, 749, 752, 751, 756, 756, 755, 742, 749, 754, 749, 756, 753, 751, 754, 752, 751, 754, 753, 749, 755, 756]
C.ToArray 772.8 ms -> [766, 772, 755, 763, 758, 767, 763, 762, 761, 768, 769, 763, 770, 757, 765, 760, 766, 759, 764, 761, 760, 777, 1102, 881, 759, 765, 758, 762, 772, 761, 758, 757, 765, 769, 769, 761, 762, 762, 763, 760, 770, 764, 760, 768, 758, 766, 763, 770, 769, 761, 764, 761, 761, 767, 761, 762, 764, 757, 765, 766, 767, 771, 753, 762, 769, 768, 759, 764, 764, 760, 763, 763, 763, 763, 763, 767, 761, 771, 760, 765, 760, 758, 768, 770, 751, 771, 767, 771, 765, 763, 760, 765, 765, 769, 767, 767, 1193, 774, 767, 764]
S.ToList 704.73 ms -> [682, 708, 705, 699, 705, 704, 695, 703, 702, 699, 701, 708, 699, 702, 703, 701, 701, 699, 701, 707, 707, 700, 701, 705, 700, 697, 706, 702, 701, 706, 699, 692, 702, 697, 707, 704, 697, 698, 699, 699, 702, 703, 698, 697, 702, 703, 702, 704, 694, 697, 707, 695, 711, 710, 700, 693, 703, 699, 699, 706, 698, 701, 703, 704, 698, 706, 700, 704, 701, 699, 702, 705, 694, 698, 709, 736, 1053, 704, 694, 700, 698, 696, 701, 700, 700, 706, 706, 692, 698, 707, 703, 695, 703, 699, 694, 708, 695, 694, 706, 695]
S.ToArray 744.17 ms -> [746, 740, 725, 740, 739, 731, 746, 760, 735, 738, 740, 734, 744, 748, 737, 744, 745, 727, 736, 738, 728, 743, 745, 735, 748, 760, 739, 748, 762, 742, 741, 747, 733, 746, 758, 742, 742, 741, 724, 744, 747, 727, 740, 740, 729, 742, 757, 741, 740, 742, 726, 739, 746, 1133, 749, 737, 730, 740, 747, 733, 747, 752, 731, 747, 742, 730, 741, 749, 731, 749, 743, 730, 747, 742, 731, 737, 745, 734, 739, 735, 727, 743, 752, 731, 744, 742, 729, 740, 746, 731, 739, 746, 733, 745, 743, 733, 739, 742, 727, 737]

C1.ToList 31.71 ms -> [35, 32, 32, 30, 31, 33, 31, 32, 32, 31, 31, 32, 32, 33, 32, 31, 31, 32, 31, 32, 32, 32, 31, 32, 33, 32, 31, 31, 31, 32, 31, 34, 31, 31, 32, 33, 32, 32, 31, 32, 34, 32, 31, 32, 33, 31, 32, 32, 31, 32, 32, 32, 32, 32, 32, 31, 31, 32, 31, 33, 30, 31, 32, 30, 30, 33, 32, 32, 34, 31, 31, 31, 31, 32, 31, 31, 31, 31, 32, 31, 31, 33, 31, 32, 32, 32, 33, 32, 31, 31, 31, 31, 31, 32, 32, 33, 32, 31, 31, 32]
C1.ToArray 59.53 ms -> [63, 57, 58, 58, 57, 59, 59, 57, 60, 131, 127, 67, 58, 56, 59, 56, 57, 58, 58, 58, 57, 59, 60, 57, 57, 59, 60, 57, 57, 57, 58, 58, 58, 58, 57, 57, 61, 57, 58, 57, 57, 57, 57, 57, 58, 58, 58, 58, 57, 58, 59, 57, 58, 57, 57, 59, 58, 58, 59, 57, 59, 57, 56, 56, 59, 56, 56, 59, 57, 58, 58, 58, 57, 58, 59, 59, 58, 57, 58, 62, 65, 57, 57, 57, 58, 60, 59, 58, 59, 57, 58, 57, 58, 59, 58, 58, 58, 59, 60, 58]
S1.ToList 82.78 ms -> [87, 82, 83, 83, 82, 82, 83, 84, 82, 83, 84, 84, 84, 82, 82, 84, 82, 84, 83, 84, 82, 82, 82, 81, 83, 83, 83, 84, 84, 82, 82, 83, 83, 83, 82, 83, 85, 83, 82, 82, 84, 82, 82, 83, 83, 83, 82, 82, 82, 83, 82, 83, 82, 84, 82, 83, 82, 83, 82, 82, 82, 84, 82, 83, 82, 82, 86, 83, 83, 82, 83, 83, 83, 82, 84, 82, 83, 81, 82, 82, 82, 82, 83, 83, 83, 82, 83, 84, 83, 82, 83, 83, 83, 82, 83, 84, 82, 82, 83, 83]
S1.ToArray 122.3 ms -> [122, 119, 119, 120, 119, 120, 120, 121, 119, 119, 122, 120, 120, 120, 122, 120, 123, 120, 120, 120, 121, 123, 120, 120, 120, 121, 120, 121, 122, 120, 123, 119, 121, 118, 121, 120, 120, 120, 119, 124, 119, 121, 119, 120, 120, 120, 120, 120, 122, 121, 123, 230, 203, 123, 119, 119, 122, 119, 120, 120, 120, 122, 120, 121, 120, 121, 120, 121, 120, 121, 120, 120, 120, 121, 122, 121, 123, 119, 119, 119, 119, 121, 120, 120, 120, 122, 121, 122, 119, 120, 120, 121, 121, 120, 121, 120, 121, 118, 118, 118]

C2.ToList 3.43 ms -> [5, 3, 4, 4, 4, 3, 4, 4, 4, 4, 4, 3, 3, 3, 4, 3, 3, 3, 4, 3, 4, 3, 4, 3, 4, 4, 3, 3, 3, 3, 4, 3, 3, 3, 4, 3, 4, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 6, 4, 4, 3, 3, 4, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 4, 3, 4, 4, 4, 3, 4, 4, 3, 4, 4, 4, 4, 4, 4, 3, 3, 3, 4, 4, 3, 3, 3, 3]
C2.ToArray 3.48 ms -> [3, 3, 3, 3, 4, 4, 3, 4, 4, 4, 3, 4, 3, 3, 4, 3, 3, 4, 3, 4, 3, 3, 3, 4, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 4, 3, 3, 4, 3, 4, 3, 3, 3, 3, 4, 3, 3, 3, 3, 4, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 4, 3, 3, 4, 3, 4, 4, 3, 4, 4, 4, 4, 4, 3, 3, 3, 4, 4, 3, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 3]
S2.ToList 41.47 ms -> [41, 41, 49, 67, 82, 41, 41, 40, 40, 40, 40, 40, 41, 40, 40, 40, 40, 40, 41, 40, 42, 42, 40, 40, 41, 41, 41, 40, 41, 40, 41, 40, 41, 40, 42, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 42, 41, 41, 41, 42, 40, 41, 40, 40, 40, 42, 40, 41, 42, 41, 42, 41, 42, 40, 41, 41, 41, 41, 41, 41, 41, 41, 40, 41, 40, 41, 41, 41, 40, 41, 41, 40, 40, 41, 41, 41, 41, 41, 43, 40, 40, 41, 42, 41]
S2.ToArray 40.62 ms -> [42, 41, 44, 40, 40, 40, 40, 41, 41, 40, 41, 41, 41, 40, 41, 41, 40, 41, 41, 40, 41, 40, 40, 41, 42, 41, 41, 41, 40, 40, 40, 40, 40, 41, 41, 42, 40, 41, 41, 41, 41, 41, 40, 42, 40, 40, 41, 41, 41, 40, 41, 40, 40, 40, 40, 40, 41, 40, 40, 41, 40, 40, 40, 40, 41, 40, 41, 41, 41, 40, 41, 41, 40, 41, 40, 41, 42, 40, 41, 41, 42, 41, 41, 40, 41, 40, 41, 40, 41, 41, 40, 40, 40, 41, 41, 40, 40, 40, 40, 40]

Due to stackoverflow's limit to the characters amount of the answer, the sample lists of Group2 and Group3 are omitted.

As you can see, it's really not important to use ToList or ToArry in most cases.

While processing runtime-calculated IEnumerable<T> objects, if the load brought by calculation is heavy than memory allocation and copy operations of ToList and ToArray, the disparity is insignificant (C.ToList vs C.ToArray and S.ToList vs S.ToArray).

The difference can be observed only on non-runtime-calculated IEnumerable<T> only objects (C1.ToList vs C1.ToArray and S1.ToList vs S1.ToArray). But the absolute difference (<60ms) is still acceptable on an one million small object IEnumerable<T>. In fact, the difference is decided by the implementation of Enumerator<T> of IEnumerable<T>. So, if your program is really really really sensitive on this, you do have to profile, profile, profile! At last you'll probably find that the bottleneck is not on ToList or ToArray, but the detail of enumerators.

And, the result of C2.ToList vs C2.ToArray and S2.ToList vs S2.ToArray shows that, you really don't need to care ToList or ToArray on non-runtime-calculated ICollection<T> objects.

Of course, this is just results on my machine, the actual time spend of these operations on different machine will not be the same, you can find out on your machine using code above.

The only reason you need to make a choice is that, you have specific needs on List<T> or T[], as described by the answer of @Jeppe Stig Nielsen.

Ewen answered 27/6, 2017 at 19:23 Comment(0)
S
5

ToListAsync<T>() is preferred.

In Entity Framework 6 both methods eventually call to the same internal method, but ToArrayAsync<T>() calls list.ToArray() at the end, which is implemented as

T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;

So ToArrayAsync<T>() has some overheads, thereby ToListAsync<T>() is preferred.

Suburbanize answered 18/1, 2018 at 3:51 Comment(2)
That's actually the answer I was looking for, how EF does it. I'd be curious how it's about in EF Core.Charlacharlady
Do you have source for this implementation? I dont see it. Looking at EF 6.4.4, ToArrayAsync is just ToListAsync<T>().ToArray()Kirven
S
1

For anyone interested in using this result in another Linq-to-sql such as

from q in context.MyTable
where myListOrArray.Contains(q.someID)
select q;

then the SQL that is generated is the same whether you used a List or Array for the myListOrArray. Now I know some may ask why even enumerate before this statement, but there is a difference between the SQL generated from an IQueryable vs (List or Array).

Stonechat answered 14/1, 2013 at 20:6 Comment(0)
J
0

I've checked the results via Benchmark.Net and seems like ToArray is slightly faster then ToList on net6

using System;
using System.Collections.Generic;
using System.Collections;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var summary = BenchmarkRunner.Run<Test>();
    }
    
    public class Test{
        
        [Benchmark]
        public List<string> ListTest() => new MyEnumerable().ToList();
        
        [Benchmark]
        public string[] ArrayTest() => new MyEnumerable().ToArray();
    }
    
    public class MyEnumerator : IEnumerator<string> {
        int counter = 0;
        
        string IEnumerator<string>.Current => counter.ToString();
        object IEnumerator.Current => counter;
        public bool MoveNext() {
            counter++;
            return counter < 10000
        }
        
        public void Reset() => counter = 0;
        
        public void Dispose() {}
    }
    
    public class MyEnumerable: IEnumerable<string> {
        IEnumerator<string> enumerator = new MyEnumerator();
        
        IEnumerator<string> IEnumerable<string>.GetEnumerator() => enumerator;
        IEnumerator IEnumerable.GetEnumerator() => enumerator;
    }
}

Result

Jiggle answered 22/8, 2023 at 15:23 Comment(1)
Please post the result of your benchmark.Paxon

© 2022 - 2024 — McMap. All rights reserved.