Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

RegexPerformanceTest

By: a guest on Aug 1st, 2012  |  syntax: Java  |  size: 1.30 KB  |  views: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import java.util.regex.PatternSyntaxException;
  2.  
  3. public class RegexPerformanceTest
  4. {
  5.         public static void main(String[] args)
  6.         {
  7.                 String regex1 = "(?im)^Hi there (.*$)(?<! is here)";
  8.                 String regex2 = "(?im)^Hi there (.*)(?<! is here)$";
  9.                 String errorTest = "Hi there John Doe is here";
  10.                 String successTest = "Hi there John Doe (jdo)";
  11.                 int repetitions = 1000000;
  12.                 try
  13.                 {
  14.                         System.out.println("Regex1, success: " + testRegexPerformance(regex1, successTest, repetitions));       // ~1200
  15.                         System.out.println("Regex1, error: " + testRegexPerformance(regex1, errorTest, repetitions));           // ~1200
  16.                         System.out.println("Regex2, success: " + testRegexPerformance(regex2, successTest, repetitions));       // ~1100
  17.                         System.out.println("Regex2, error: " + testRegexPerformance(regex2, errorTest, repetitions));           // ~1800
  18.                 }
  19.                 catch(PatternSyntaxException e)
  20.                 {
  21.                         e.printStackTrace();
  22.                 }
  23.         }
  24.  
  25.         private static long testRegexPerformance(String regex, String subject, int numberOfRepetitions) throws PatternSyntaxException
  26.         {
  27.                 boolean foundMatch;
  28.                 long endTime = 0;
  29.                 long startTime = 0;
  30.                 startTime = System.currentTimeMillis();
  31.                 for (int i = 0; i < numberOfRepetitions; i++)
  32.                 {
  33.                         foundMatch = subject.matches(regex);
  34.                 }
  35.                 endTime = System.currentTimeMillis();
  36.                 return endTime - startTime;
  37.         }
  38. }