Skip to content

Instantly share code, notes, and snippets.

@CarlosLanderas
Created July 3, 2018 22:40
Show Gist options
  • Save CarlosLanderas/fcddb039ae88242f64f37671e0e478aa to your computer and use it in GitHub Desktop.
Save CarlosLanderas/fcddb039ae88242f64f37671e0e478aa to your computer and use it in GitHub Desktop.
Span<T> benchmarks
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Jobs;
using BenchmarkDotNet.Running;
using System;
using System.ComponentModel;
namespace PropertyCache
{
[ClrJob, MonoJob, CoreJob]
[MemoryDiagnoser]
public class Benchmarks
{
static void Main(string[] args)
{
BenchmarkRunner.Run<Benchmarks>();
}
[GlobalSetup]
public void Setup()
{
var bytes = new byte[100];
new Random(42).NextBytes(bytes);
stringNumbers = string.Join(";", Array.ConvertAll(bytes, Convert.ToInt32));
}
public static string stringNumbers = string.Empty;
public static string contentLength = "content-length:534";
[Benchmark]
public static int SumStringNumbers()
{
int sum = 0;
var numbers = stringNumbers.Split(";");
foreach (var num in numbers)
{
sum += int.Parse(num);
}
return sum;
}
[Benchmark]
public static int SumStringNumbersWithSpan()
{
int sum = 0;
ReadOnlySpan<char> span = stringNumbers;
while (true)
{
int index = span.IndexOf(';');
if (index == -1)
{
sum += int.Parse(span);
break;
}
sum += int.Parse(span.Slice(0, index));
span = span.Slice(index + 1);
}
return sum;
}
[Benchmark]
public static int ParseContentLength() => Int32.Parse(contentLength.Substring(15));
[Benchmark]
public static int ParseContentLengthWithSpan() => Int32.Parse(contentLength.AsSpan().Slice(15));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment