What\'s the difference between String.matches and Matcher.matches? Is there any difference in terms of performance or other things?
Out of curiosity I did this small test on the time differences. Turns out that using a pre-compiled pattern is more than 5 times faster than using String.matches method.
import java.util.regex.Pattern;
/**
* @author Rajind Ruparathna
*/
public class MatchesTest {
public static void main(String Args[]) {
String first = "@\\{message.headers\\.?([^\\}]*)\\}";
String second = "@\\{message.headers.wolla\\}";
long start, end, total;
float avg;
int NUM_OF_ITERATIONS = 100;
Pattern pattern = Pattern.compile(first);
total = 0;
start = 0;
end = 0;
avg = 0;
for (int i=0; i< NUM_OF_ITERATIONS; i++) {
start = System.nanoTime();
pattern.matcher(second).matches();
end = System.nanoTime();
total = total + (end - start);
}
avg = total/NUM_OF_ITERATIONS;
System.out.println("Duration pre compiled: " + avg);
total = 0;
start = 0;
end = 0;
avg = 0;
for (int i=0; i< NUM_OF_ITERATIONS; i++) {
start = System.nanoTime();
first.matches(second);
end = System.nanoTime();
total = total + (end - start);
}
avg = total/NUM_OF_ITERATIONS;
System.out.println("In place compiled: " + avg);
}
}
Output (nanoseconds):
Duration pre compiled: 4505.0
In place compiled: 44960.0
P.S. This test is a quick and dirty test and may not be according to performance benchmarking practises. If you want to get highly accurate results please use a micro benchmarking tool.