Skip to content

Instantly share code, notes, and snippets.

@svick
Last active March 3, 2020 20:04
Show Gist options
  • Select an option

  • Save svick/3990b6ccedf3a80f068b52d9fa0830e6 to your computer and use it in GitHub Desktop.

Select an option

Save svick/3990b6ccedf3a80f068b52d9fa0830e6 to your computer and use it in GitHub Desktop.
head-tail sum perf
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Running;
public class Program
{
static void Main() => BenchmarkRunner.Run<Benchmark>();
}
[MemoryDiagnoser]
public class Benchmark
{
List<int> list = Enumerable.Range(1, 1_000).ToList();
[Benchmark]
public int LinqSum()
{
return list.Sum();
}
[Benchmark]
public int ListDeconstruct()
{
int Sum(List<int> list)
{
switch (list.Count)
{
case 0:
return 0;
default:
var (head, tail) = list;
return head + Sum(tail);
}
}
return Sum(list);
}
[Benchmark]
public int EnumerableDeconstruct()
{
int Sum(IEnumerable<int> list)
{
switch (list.Count())
{
case 0:
return 0;
default:
var (head, tail) = list;
return head + Sum(tail);
}
}
return Sum(list);
}
[Benchmark]
public int SpanDeconstruct()
{
int Sum(Span<int> list)
{
switch (list.Length)
{
case 0:
return 0;
default:
var (head, tail) = list;
return head + Sum(tail);
}
}
return Sum(CollectionsMarshal.AsSpan(list));
}
}
static class E
{
public static void Deconstruct<T>(this List<T> list, out T head, out List<T> tail)
{
head = list.FirstOrDefault();
tail = new List<T>(list.Skip(1));
}
public static void Deconstruct<T>(this IEnumerable<T> list, out T head, out IEnumerable<T> tail)
{
head = list.FirstOrDefault();
tail = list.Skip(1);
}
public static void Deconstruct<T>(this Span<T> list, out T head, out Span<T> tail)
{
head = list.Length == 0 ? default : list[0];
tail = list.Slice(1);
}
}
BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18362
Intel Core i5-2300 CPU 2.80GHz (Sandy Bridge), 1 CPU, 4 logical and 4 physical cores
.NET Core SDK=5.0.100-alpha.1.20060.7
  [Host]     : .NET Core 5.0.0 (CoreCLR 5.0.20.6002, CoreFX 5.0.20.6002), X64 RyuJIT
  DefaultJob : .NET Core 5.0.0 (CoreCLR 5.0.20.6002, CoreFX 5.0.20.6002), X64 RyuJIT
Method Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
LinqSum 10.55 us 0.073 us 0.065 us - - - 40 B
ListDeconstruct 10,023.12 us 150.070 us 140.375 us 1000.0000 406.2500 - 5642989 B
EnumerableDeconstruct 87.94 us 1.103 us 1.032 us 15.2588 - - 48000 B
SpanDeconstruct 17.50 us 0.152 us 0.142 us - - - -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment