Here is a benchmark of regionMatches. We can use regionMatches for some significant performance wins in real-world Java programs.
public class Program {
public static void main(String[] args) {
String part1 =
"CatDogBird";
String part2 =
"DogBirdCat";
// Test two versions.
if (part1.regionMatches(3, part2, 0, 3)) {
System.out.println(
"True 1");
}
if (part1.substring(3, 6).equals(part2.substring(0, 3))) {
System.out.println(
"True 2");
}
int count = 0;
long t1 = System.currentTimeMillis();
// Version 1: use regionMatches to compare two substrings.
for (int i = 0; i < 10000000; i++) {
if (part1.regionMatches(3, part2, 0, 3)) {
count++;
}
}
long t2 = System.currentTimeMillis();
// Version 2: use substring to compare two substrings.
for (int i = 0; i < 10000000; i++) {
if (part1.substring(3, 6).equals(part2.substring(0, 3))) {
count++;
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(count);
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
True 1
True 2
20000000
15 ms: regionMatches
172 ms: substring, equals