Here's a really rather crude benchmark to give you an idea. Adapt it to your use cases to give you more relevant results.
TL;DR
startsWith() and endsWith() are much faster
Detailed results
Results after 1 000 000 runs:
- Uncompiled pattern: 1091 ms
- Compiled pattern: 745 ms
- startsWith() / endsWith(): 24 ms
public class TestRegex {
String regex = "^start.*end$";
Pattern p = Pattern.compile(regex);
String start = "start";
String end = "end";
String search = start + "fewbjlhfgljghfadsjhfdsaglfdhjgahfgfjkhgfdkhjsagafdskghjafdkhjgfadskhjgfdsakhjgfdaskhjgafdskjhgafdsjhkgfads" + end;
int runs = 1000000;
@Test
public final void test() {
// Init run
for (int i = 0; i < runs; i++) {
search.matches(regex);
}
for (int i = 0; i < runs; i++) {
p.matcher(search).matches();
}
for (int i = 0; i < runs; i++) {
search.startsWith(start);
search.endsWith(end);
}
// Timed run
Stopwatch s = Stopwatch.createStarted();
for (int i = 0; i < runs; i++) {
search.matches(regex);
}
System.out.println(s.elapsed(TimeUnit.MILLISECONDS));
s.reset();
s.start();
for (int i = 0; i < runs; i++) {
p.matcher(search).matches();
}
System.out.println(s.elapsed(TimeUnit.MILLISECONDS));
s.reset();
s.start();
for (int i = 0; i < runs; i++) {
search.startsWith(start);
search.endsWith(end);
}
System.out.println(s.elapsed(TimeUnit.MILLISECONDS));
}
}