Advertisement
Guest User

Untitled

a guest
Oct 30th, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. package com.ouroboros.experiment.parsetest;
  2.  
  3. import java.util.concurrent.Callable;
  4. import java.util.regex.Pattern;
  5.  
  6. import org.apache.commons.lang3.math.NumberUtils;
  7. import org.apache.commons.validator.routines.IntegerValidator;
  8.  
  9. public class App {
  10.     public static void measure(String name, Callable<Integer> what) throws Exception {
  11.         int iterations = 1000000;
  12.         long starttime = System.currentTimeMillis();
  13.  
  14.         for (int i = 0; i < iterations; i++) {
  15.             if (what.call() != 434378) throw new Exception("Parsing gave invalid results!");
  16.         }
  17.  
  18.         long endtime = System.currentTimeMillis();
  19.         System.out.println(name + ": " + (endtime - starttime) + " ms.");
  20.     }
  21.  
  22.     private static Callable<Integer> ParseWithTryCatch = new Callable<Integer>() {
  23.  
  24.         public Integer call() throws Exception {
  25.             try {
  26.                 return Integer.parseInt("434378");
  27.             } catch (NumberFormatException nfe) {
  28.             }
  29.  
  30.             return 0;
  31.         }
  32.     };
  33.  
  34.     private static Callable<Integer> ParseWithRegexCheck = new Callable<Integer>() {
  35.  
  36.         public Integer call() throws Exception {
  37.             return INT_PATTERN.matcher("434378").matches() ? Integer.parseInt("434378") : 0;
  38.         }
  39.     };
  40.  
  41.     private static Pattern INT_PATTERN = Pattern.compile("^[-0-9]+$");
  42.  
  43.     private static Callable<Integer> ParseWithValidator = new Callable<Integer>() {
  44.  
  45.         public Integer call() throws Exception {
  46.             return IntegerValidator.getInstance().validate("434378");
  47.         }
  48.     };
  49.    
  50.     private static Callable<Integer> ParseWithNumberUtils = new Callable<Integer>() {
  51.  
  52.         public Integer call() throws Exception {
  53.             return NumberUtils.toInt("434378");
  54.         }
  55.     };
  56.  
  57.     public static void main(String[] args) throws Exception {
  58.         measure("try-catch", ParseWithTryCatch);
  59.         measure("regex", ParseWithRegexCheck);
  60.         measure("validator", ParseWithValidator);
  61.         measure("numberutils", ParseWithNumberUtils);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement