Skip to content

Instantly share code, notes, and snippets.

@JakobFerdinand
Last active October 1, 2018 10:49
Show Gist options
  • Save JakobFerdinand/0ff7856a18f9c24526ed16f6b5069c4d to your computer and use it in GitHub Desktop.
Save JakobFerdinand/0ff7856a18f9c24526ed16f6b5069c4d to your computer and use it in GitHub Desktop.
A performance comparison between ToArray() vs ToImmutableList().
#r ".\System.Collections.Immutable"
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using static System.Console;
class Person
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
var data = Enumerable.Range(0, 100000).Select(i => new Person { Id = i, Firstname = $"Vorname {i}", Lastname = $"Nachname {i}" }).ToList();
long TestToArray()
=> Enumerable.Range(0, 10000)
.Select(_ =>
{
var sw = new Stopwatch();
sw.Start();
data.ToArray();
sw.Stop();
return sw.ElapsedMilliseconds;
})
.Sum();
long TestToImmutableList()
=> Enumerable.Range(0, 10000)
.Select(_ =>
{
var sw = new Stopwatch();
sw.Start();
data.ToImmutableList();
sw.Stop();
return sw.ElapsedMilliseconds;
})
.Sum();
WriteLine(TestToArray());
WriteLine(TestToImmutableList());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment