Create a gist now

Instantly share code, notes, and snippets.

Embed
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ImmutableVsMutablePerformanceComparison
{
class SmallImmutableClass
{
public int A { get; }
public SmallImmutableClass(int a)
{
A = a;
}
public SmallImmutableClass Move(int x)
{
return new SmallImmutableClass(A+x);
}
}
class BigImmutableClass
{
public IReadOnlyCollection<int> A { get; }
public BigImmutableClass(IEnumerable<int> a)
{
A = a.ToList();
}
public BigImmutableClass Move(int x)
{
return new BigImmutableClass(A.Select(elem => elem+x));
}
}
class SmallMutableClass
{
public int A { get; private set; }
public SmallMutableClass(int a)
{
A = a;
}
public void Move(int x)
{
A += x;
}
}
class BigMutableClass
{
public int[] A { get; }
public BigMutableClass(IEnumerable<int> a)
{
A = a.ToArray();
}
public void Move(int x)
{
for (int i = 0; i < A.Length; i++)
{
A[i] += x;
}
}
}
class Program
{
static void Main(string[] args)
{
var sw = new Stopwatch();
var tests = 100000;
var sizeOfBigClasses = 20000;
var sic = new SmallImmutableClass(0);
sw.Start();
for (int i = 0; i < tests; i++)
{
sic = sic.Move(i);
}
Console.WriteLine(sw.Elapsed);
sw.Restart();
var smc = new SmallMutableClass(0);
for (int i = 0; i < tests; i++)
{
smc.Move(i);
}
Console.WriteLine(sw.Elapsed);
sw.Restart();
var bic = new BigImmutableClass(Enumerable.Range(0, sizeOfBigClasses));
for (int i = 0; i < tests; i++)
{
bic = bic.Move(i);
}
Console.WriteLine(sw.Elapsed);
sw.Restart();
var bmc = new BigMutableClass(Enumerable.Range(0, sizeOfBigClasses));
for (int i = 0; i < tests; i++)
{
bmc.Move(i);
}
Console.WriteLine(sw.Elapsed);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment