Last active
June 29, 2018 08:47
-
-
Save lahma/5cc6cd7d2b92a875ce98c6549d8c1dd6 to your computer and use it in GitHub Desktop.
Parsing positive integers faster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.