Skip to content

Instantly share code, notes, and snippets.

@lahma
Last active June 29, 2018 08:47
Show Gist options
  • Select an option

  • Save lahma/5cc6cd7d2b92a875ce98c6549d8c1dd6 to your computer and use it in GitHub Desktop.

Select an option

Save lahma/5cc6cd7d2b92a875ce98c6549d8c1dd6 to your computer and use it in GitHub Desktop.
Parsing positive integers faster
using System;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
namespace Jint.Benchmark
{
[MemoryDiagnoser]
public class IntParseBenchmark
{
private const int N = 1_000_000;
private static readonly string NString = N.ToString();
[Benchmark]
public long ConvertToInt32Substring()
{
long sum = 0;
for (int i = 0; i < N; ++i)
{
sum += Convert.ToInt32(NString.Substring(0, NString.Length - 1));
}
return sum;
}
[Benchmark]
public long IntParseFast()
{
long sum = 0;
for (int i = 0; i < N; ++i)
{
sum += IntParseFast(NString, 0, NString.Length - 1);
}
return sum;
}
[Benchmark]
public long IntParseFastUint()
{
long sum = 0;
for (int i = 0; i < N; ++i)
{
sum += IntParseFastU(NString, 0, NString.Length - 1);
}
return sum;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IntParseFast(string value, int startIndex, int endIndex)
{
int result = 0;
int length = endIndex;
for (int i = startIndex; i < length; i++)
{
result = 10 * result + (value[i] - 48);
}
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IntParseFastU(string value, int startIndex, int endIndex)
{
int result = 0;
int length = endIndex;
for (int i = startIndex; i < (uint) length; i++)
{
result = 10 * result + (value[i] - 48);
}
return result;
}
}
}
@lahma
Copy link
Copy Markdown
Author

lahma commented Jun 29, 2018

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-6820HQ CPU 2.70GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.301
  [Host]     : .NET Core 2.0.7 (CoreCLR 4.6.26328.01, CoreFX 4.6.26403.03), 64bit RyuJIT
  DefaultJob : .NET Core 2.0.7 (CoreCLR 4.6.26328.01, CoreFX 4.6.26403.03), 64bit RyuJIT

Method Mean Error StdDev Gen 0 Allocated
ConvertToInt32Substring 126.454 ms 0.7954 ms 0.7441 ms 9500.0000 40000000 B
IntParseFast 5.754 ms 0.0390 ms 0.0365 ms - 0 B
IntParseFastUint 5.028 ms 0.0293 ms 0.0260 ms - 0 B

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment