Created
July 21, 2017 08:24
-
-
Save alex-fomin/8a53c35bd6e2f95c97faefbd4d192c67 to your computer and use it in GitHub Desktop.
ToArray vs ToList vs ToImmutableArray vs ToImmutableList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Collections.Immutable; | |
using System.Linq; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
BenchmarkRunner.Run<Bench>(); | |
} | |
} | |
public class Bench | |
{ | |
private const int _count = 10000; | |
IEnumerable<int> Do(Func<IEnumerable<int>, IEnumerable<int>>f) => | |
f(f(Enumerable.Range(0, _count)).Where(x => x % 2 == 0)); | |
[Benchmark] | |
public IEnumerable<int> ToImmutableArray() => Do(x => x.ToImmutableArray()); | |
[Benchmark] | |
public IEnumerable<int> ToArray() => Do(x => x.ToArray()); | |
[Benchmark] | |
public IEnumerable<int> ToList() => Do(x => x.ToList()); | |
[Benchmark] | |
public IEnumerable<int> ToImmutableList() => Do(x => x.ToImmutableList()); | |
} | |
} |
Super late but result is here: https://der-waldgeist.blogspot.com/2017/07/toarray-vs-tolist-vs-toimmutablearray.html
Slightly modified:
public class Bench
{
private const int _count = 10000;
IEnumerable<int> Do(Func<IEnumerable<int>, IEnumerable<int>> f) =>
f(f(Enumerable.Range(0, _count)));
[Benchmark]
public ImmutableArray<int> ToImmutableArray() => (ImmutableArray<int>)Do(x => x.ToImmutableArray());
[Benchmark]
public int[] ToArray() => (int[])Do(x => x.ToArray());
[Benchmark]
public List<int> ToList() => (List<int>)Do(x => x.ToList());
[Benchmark]
public IImmutableList<int> ToImmutableList() => (IImmutableList<int>)Do(x => x.ToImmutableList());
}
Result:
// * Summary *
BenchmarkDotNet v0.13.6, Windows 11 (10.0.22621.1992/22H2/2022Update/SunValley2)
Intel Core i7-7700K CPU 4.20GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
.NET SDK 7.0.306
[Host] : .NET 7.0.9 (7.0.923.32018), X64 RyuJIT AVX2
DefaultJob : .NET 7.0.9 (7.0.923.32018), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev |
|----------------- |-----------:|----------:|----------:|
| ToImmutableArray | 5.024 us | 0.0841 us | 0.1002 us |
| ToArray | 6.907 us | 0.0611 us | 0.0510 us |
| ToList | 17.291 us | 0.2834 us | 0.2512 us |
| ToImmutableList | 178.526 us | 0.9276 us | 0.7242 us |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So the result is ?