Last active
March 22, 2017 20:14
-
-
Save Tamschi/f9e3103721c8026638ac960f3f209eb1 to your computer and use it in GitHub Desktop.
Integer Speedparser
This file contains 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
public static int Parse(string str) | |
{ | |
unchecked | |
{ | |
int n = 0; | |
int l = str.Length - 1; | |
for (int i = l, x = 1; i >= 0; i--, x *= 10) | |
{ | |
switch (str[i]) | |
{ | |
case '0': | |
break; | |
case '1': | |
n += x; | |
break; | |
case '2': | |
n += 2 * x; | |
break; | |
case '3': | |
n += 3 * x; | |
break; | |
case '4': | |
n += 4 * x; | |
break; | |
case '5': | |
n += 5 * x; | |
break; | |
case '6': | |
n += 6 * x; | |
break; | |
case '7': | |
n += 7 * x; | |
break; | |
case '8': | |
n += 8 * x; | |
break; | |
case '9': | |
n += 9 * x; | |
break; | |
default: | |
if (i == 0 && str[0] == '-') return -n; | |
throw new ArgumentException($"The argument {nameof(str)} is not a number."); | |
} | |
} | |
return n; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didn't test if this is actually faster.