Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.ouroboros.experiment.parsetest;
- import java.util.concurrent.Callable;
- import java.util.regex.Pattern;
- import org.apache.commons.lang3.math.NumberUtils;
- import org.apache.commons.validator.routines.IntegerValidator;
- public class App {
- public static void measure(String name, Callable<Integer> what) throws Exception {
- int iterations = 1000000;
- long starttime = System.currentTimeMillis();
- for (int i = 0; i < iterations; i++) {
- if (what.call() != 434378) throw new Exception("Parsing gave invalid results!");
- }
- long endtime = System.currentTimeMillis();
- System.out.println(name + ": " + (endtime - starttime) + " ms.");
- }
- private static Callable<Integer> ParseWithTryCatch = new Callable<Integer>() {
- public Integer call() throws Exception {
- try {
- return Integer.parseInt("434378");
- } catch (NumberFormatException nfe) {
- }
- return 0;
- }
- };
- private static Callable<Integer> ParseWithRegexCheck = new Callable<Integer>() {
- public Integer call() throws Exception {
- return INT_PATTERN.matcher("434378").matches() ? Integer.parseInt("434378") : 0;
- }
- };
- private static Pattern INT_PATTERN = Pattern.compile("^[-0-9]+$");
- private static Callable<Integer> ParseWithValidator = new Callable<Integer>() {
- public Integer call() throws Exception {
- return IntegerValidator.getInstance().validate("434378");
- }
- };
- private static Callable<Integer> ParseWithNumberUtils = new Callable<Integer>() {
- public Integer call() throws Exception {
- return NumberUtils.toInt("434378");
- }
- };
- public static void main(String[] args) throws Exception {
- measure("try-catch", ParseWithTryCatch);
- measure("regex", ParseWithRegexCheck);
- measure("validator", ParseWithValidator);
- measure("numberutils", ParseWithNumberUtils);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement