Last active
December 25, 2015 01:59
-
-
Save willemsst/6898876 to your computer and use it in GitHub Desktop.
stupid int parse test
-> stupid int parsing almost twice as fast as the one from the JDK (1.6) Total time: 2.5252283s
Avg time: 25.252283ns Total time: 4.094798s
Avg time: 40.94798ns
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
import org.junit.Test; | |
public class IntParseTest { | |
private static int parseInt(String s) { | |
int result = 0; | |
char x; | |
boolean negative = false; | |
for (int i = 0; i < s.length(); i++) { | |
x = s.charAt(i); | |
switch (x) { | |
case '1': | |
case '2': | |
case '3': | |
case '4': | |
case '5': | |
case '6': | |
case '7': | |
case '8': | |
case '9': | |
case '0': | |
result = result * 10 + (x - 48); | |
break; | |
case '-': | |
negative = true; | |
break; | |
default: | |
throw new NumberFormatException(s); | |
} | |
} | |
if (negative) { | |
return -1 * result; | |
} else { | |
return result; | |
} | |
} | |
@Test | |
public void test() { | |
int actual = 0; | |
int iterations = 100000000; | |
String input = "-122312345"; | |
long start = System.nanoTime(); | |
for (int i = 0; i < iterations; i++) { | |
actual = parseInt(input); | |
} | |
long duration = System.nanoTime() - start; | |
System.out.println("Total time: " + (duration / (1000 * 1000 * 1000f)) + "s"); | |
System.out.println("Avg time: " + (duration * 1f / iterations) + "ns"); | |
start = System.nanoTime(); | |
for (int i = 0; i < iterations; i++) { | |
actual = Integer.parseInt(input); | |
} | |
duration = System.nanoTime() - start; | |
System.out.println("Total time: " + (duration / (1000 * 1000 * 1000f)) + "s"); | |
System.out.println("Avg time: " + (duration * 1f / iterations) + "ns"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't deal well with invalid inputs that consist of legal characters, though. e.g. 145-5721-5