Last active
August 29, 2015 14:05
-
-
Save kentan/bc0f2f4bc58fc84681cc to your computer and use it in GitHub Desktop.
Sample code for the performance difference among the regular expression quantifiers .
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 java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class RegExpTest1 { | |
private static String str = "xfooxxxxxxfoo"; | |
private static int max = 10000000; | |
public static void main(String args[]){ | |
runGreedy(); | |
runReluctant(); | |
runPossessive(); | |
} | |
public static void runGreedy(){ | |
long before = System.currentTimeMillis(); | |
String regex = ".*foo"; | |
for(int i = 0; i < max ; i++){ | |
Pattern p = Pattern.compile(regex); | |
Matcher m = p.matcher(str); | |
m.find(); | |
} | |
long after = System.currentTimeMillis(); | |
System.out.println("greedy :" + (after - before)); | |
} | |
public static void runReluctant(){ | |
long before = System.currentTimeMillis(); | |
String regex = ".*?foo"; | |
for(int i = 0; i < max ; i++){ | |
Pattern p = Pattern.compile(regex); | |
Matcher m = p.matcher(str); | |
m.find(); | |
} | |
long after = System.currentTimeMillis(); | |
System.out.println("reluctant :" + (after - before)); | |
} | |
public static void runPossessive(){ | |
long before = System.currentTimeMillis(); | |
String regex = ".*+foo"; | |
for(int i = 0; i < max ; i++){ | |
Pattern p = Pattern.compile(regex); | |
Matcher m = p.matcher(str); | |
m.find(); | |
} | |
long after = System.currentTimeMillis(); | |
System.out.println("possessive :" + (after - before)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment