Skip to content

Instantly share code, notes, and snippets.

@kshyju
Created March 22, 2021 06:50
Show Gist options
  • Save kshyju/6950df47e319f31b544a846987b478d6 to your computer and use it in GitHub Desktop.
Save kshyju/6950df47e319f31b544a846987b478d6 to your computer and use it in GitHub Desktop.
SliceToMultiple-SpanVsSubString
using BenchmarkDotNet.Attributes;
using System;
using System.Collections.Generic;
namespace Benchmark_ToListCall
{
[MemoryDiagnoser]
public class StringBenchmarks2
{
private string stringToSlice;
[GlobalSetup]
public void Init()
{
this.stringToSlice = "Lorem ipsum dolor sit amet";
}
[Benchmark]
public List<string> WithSpan()
{
return SliceToMultipleSpan(this.stringToSlice, 3);
}
[Benchmark]
public List<string> WithoutSpan()
{
return SliceToMultiple(this.stringToSlice, 3);
}
List<string> SliceToMultiple(string value, int sliceLength)
{
if (value == null)
{
value = string.Empty;
}
var resultList = new List<string>(value.Length / sliceLength);
var startIndexToSliceFrom = 0;
var totalLengthSliced = 0;
while (totalLengthSliced < value.Length)
{
var lengthToSlice = Math.Min(sliceLength, value.Length - totalLengthSliced);
resultList.Add(value.Substring(startIndexToSliceFrom, lengthToSlice));
totalLengthSliced = totalLengthSliced + lengthToSlice;
startIndexToSliceFrom = totalLengthSliced;
}
return resultList;
}
List<string> SliceToMultipleSpan(string value, int sliceLength)
{
if (value == null)
{
value = string.Empty;
}
var resultList = new List<string>(value.Length / sliceLength);
var startIndexToSliceFrom = 0;
var totalLengthSliced = 0;
var valueSpan = value.AsSpan();
while (totalLengthSliced < value.Length)
{
var lengthToSlice = Math.Min(sliceLength, value.Length - totalLengthSliced);
resultList.Add(valueSpan.Slice(startIndexToSliceFrom, lengthToSlice).ToString());
totalLengthSliced = totalLengthSliced + lengthToSlice;
startIndexToSliceFrom = totalLengthSliced;
}
return resultList;
}
}
}
``` ini
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.21340
Intel Xeon CPU E5-1650 v4 3.60GHz, 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=5.0.201
[Host] : .NET Core 3.1.13 (CoreCLR 4.700.21.11102, CoreFX 4.700.21.11602), X64 RyuJIT
DefaultJob : .NET Core 3.1.13 (CoreCLR 4.700.21.11102, CoreFX 4.700.21.11602), X64 RyuJIT
```
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------ |---------:|--------:|--------:|-------:|-------:|------:|----------:|
| WithSpan | 203.8 ns | 4.10 ns | 6.00 ns | 0.0713 | 0.0002 | - | 560 B |
| WithoutSpan | 203.9 ns | 4.14 ns | 8.46 ns | 0.0713 | 0.0002 | - | 560 B |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment