Skip to content

Instantly share code, notes, and snippets.

@deepumi
Last active April 15, 2020 19:47
Show Gist options
  • Save deepumi/1ce6ec46c353f17cf13d06996803a921 to your computer and use it in GitHub Desktop.
Save deepumi/1ce6ec46c353f17cf13d06996803a921 to your computer and use it in GitHub Desktop.
Convert StringArray to Integer Array
using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
using BenchmarkDotNet.Running;
namespace App
{
public sealed class Program
{
public static void Main()
{
var summary = BenchmarkRunner.Run(typeof(BenchmarkTest).Assembly);
}
}
[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class BenchmarkTest
{
private const string Content = "24,25,19,16,18";
[Benchmark]
public void StringToIntArray()
{
var myIntegers = new List<int>();
Array.ForEach(Content.Split(",".ToCharArray()), s =>
{
if (Int32.TryParse(s, out int currentInt))
myIntegers.Add(currentInt);
else
myIntegers.Add(0);
});
var result = myIntegers.ToArray();
}
[Benchmark]
public void Split()
{
var split = Content?.Split(',', StringSplitOptions.RemoveEmptyEntries);
var result = new int[split.Length];
for (var i = 0; i < split.Length; i++)
{
if (int.TryParse(split[i], out var value))
{
result[i] = value;
}
else
{
result[i] = 0;
}
}
}
[Benchmark]
public void NoSplitWithList()
{
var chars = new List<int>();
var val = 0;
var j = 0;
for (; j < Content.Length; j++)
{
if (Content[j] == ',')
{
chars.Add(val);
val = 0;
}
else
{
val *= 10;
val += Content[j] - '0';
}
}
if (val > 0) chars.Add(val);
}
[Benchmark]
public void NoSplitWithReadOnlySpan()
{
ReadOnlySpan<char> span = Content;
var counter = 0;
for (var i = 0; i < span.Length; i++)
{
if (span[i] == ',')
{
counter++;
}
}
var chars = new int[counter+1];
var val = 0;
var jj = 0;
for (var j = 0; j < span.Length; j++)
{
if (span[j] == ',')
{
chars[jj] = val;
val = 0;
jj++;
}
else
{
val *= 10;
val += span[j] - '0';
}
}
if (val > 0) chars[jj++] = val;
}
}
}
//Benchmark result
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18362.720 (1903/May2019Update/19H1)
Intel Core i7-8565U CPU 1.80GHz (Whiskey Lake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.200-preview-015002
[Host] : .NET Core 3.1.2 (CoreCLR 4.700.20.6602, CoreFX 4.700.20.6702), X64 RyuJIT [AttachedDebugger]
DefaultJob : .NET Core 3.1.2 (CoreCLR 4.700.20.6602, CoreFX 4.700.20.6702), X64 RyuJIT
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------------------ |----------:|---------:|----------:|-------:|------:|------:|----------:|
| NoSplitWithReadOnlySpan | 32.99 ns | 0.686 ns | 1.218 ns | 0.0114 | - | - | 48 B |
| NoSplitWithList | 78.81 ns | 1.606 ns | 4.423 ns | 0.0305 | - | - | 128 B |
| Split | 209.87 ns | 1.941 ns | 1.721 ns | 0.0648 | - | - | 272 B |
| StringToIntArray | 335.23 ns | 6.962 ns | 19.976 ns | 0.1240 | - | - | 520 B |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment