RegionMatches
This method tests a region of one string
against another. We provide a start index for both strings. We also provide a length argument (the number of chars to test on both).
With regionMatches
, we can see if a substring patches another substring. We can avoid creating substrings. This saves allocations and improves performance.
Let us begin with this example. We have a string
literal with four concatenated words in it. We match each part of this literal.
regionMatches
ignore the case of characters by passing a value of "true" as the first argument.public class Program { public static void main(String[] args) { String codes = "OneTwoThreeFour"; // Check for "Two" at index 3. // ... Length is 3 chars. if (codes.regionMatches(3, "Two", 0, 3)) { System.out.println(true); } // Check for "Three" at index 6. // ... Length is 5 chars. if (codes.regionMatches(6, "Three", 0, 5)) { System.out.println(true); } // Check for "FOUR" from "IS_FOUR" at index 11. // ... Length is 4 chars. if (codes.regionMatches(true, 11, "IS_FOUR", 3, 4)) { System.out.println(true); } } }true true true
Here is a benchmark of regionMatches
. We can use regionMatches
for some significant performance wins in real-world Java programs.
regionMatches
method to compare 2 substring parts.equals()
.RegionMatches
is faster. In this benchmark regionMatches
is over 10 times faster than the version that uses substring and equals.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
When using methods like regionMatches
and substring()
, using correct indexes and lengths is important. The final argument on regionMatches
is a length.
Avoiding allocations is one of the best performance optimizations. With regionMatches
, we can achieve a big performance win if we can reduce substring allocations.
The arguments to regionMatches
can be hard to get right at first. But the performance and code size improvements with regionMatches
makes it worth the effort.