我用 caliper 测试了这个和这个,结果是:如果你在每个方法调用之前编译 Pattern,这将是最快的方法。
您的正则表达式方法是最快的方法,但是您需要做的唯一更改是预先计算 Pattern ,而不是每次:
private static Pattern p = Pattern.compile(VALID_DOMAIN);
然后在你的方法中:
Matcher matcher = pattern.matcher(input); ...
对于感兴趣的人,这是我用于卡尺的设置:--warmupMillis 10000 --runMillis 100
package stackoverflow;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
public class RegexPerformance extends SimpleBenchmark {
private static final String firstPart = "technology|computer|sdc|adj|wdc|pp|stub";
private static final String secondPart = "profile|preference|experience|behavioral";
private static final String VALID_DOMAIN = "(technology|computer|sdc|adj|wdc|pp|stub)\\.(profile|preference|experience|behavioral)";
@Param({"technology.profile.financial", "computer.preference.test","sdc.experience.test"})
private String input;
public static void main(String[] args) {
Runner.main(RegexPerformance.class, args);
}
public void timeRegexMatch(int reps){
for(int i=0;i<reps;++i){
regexMatch(input);
}
}
public void timeGuavaMatch(int reps){
for(int i=0;i<reps;++i){
guavaMatch(input);
}
}
public void timeRegexMatchOutsideMethod(int reps){
for(int i=0;i<reps;++i){
regexMatchOutsideMethod(input);
}
}
public String regexMatch(String input){
Pattern p = Pattern.compile(VALID_DOMAIN);
Matcher m = p.matcher(input);
if(m.find()) return m.group();
return null;
}
public String regexMatchOutsideMethod(String input){
Matcher matcher = pattern.matcher(input);
if(matcher.find()) return matcher.group();
return null;
}
public String guavaMatch(String input){
Iterable<String> tokens = Splitter.on(".").omitEmptyStrings().split(input);
String firstToken = Iterables.get(tokens, 0);
String secondToken = Iterables.get(tokens, 1);
if( (firstPart.contains(firstToken) ) && (secondPart.contains(secondToken)) ){
return firstToken+"."+secondToken;
}
return null;
}
}
以及测试结果:
RegexMatch technology.profile.financial 2980 ========================
RegexMatch computer.preference.test 2861 =======================
RegexMatch sdc.experience.test 3683 ==============================
RegexMatchOutsideMethod technology.profile.financial 179 =
RegexMatchOutsideMethod computer.preference.test 227 =
RegexMatchOutsideMethod sdc.experience.test 987 ========
GuavaMatch technology.profile.financial 406 ===
GuavaMatch computer.preference.test 421 ===
GuavaMatch sdc.experience.test 382 ===