Skip to content

Instantly share code, notes, and snippets.

@kentan
Last active August 29, 2015 14:05
Show Gist options
  • Save kentan/bc0f2f4bc58fc84681cc to your computer and use it in GitHub Desktop.
Save kentan/bc0f2f4bc58fc84681cc to your computer and use it in GitHub Desktop.
Sample code for the performance difference among the regular expression quantifiers .
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