Compare first three characters of two strings
java
Solution
Rewrite to avoid object creation
Your instincts were correct. The creation of new objects (substring()) is not very fast and it means that each one created must incur g/c overhead as well.
This might be a lot faster:
static boolean fastCmp(String s1, String s2) {
return s1.regionMatches(0, s2, 0, 3);
}
Problem
Strings s1 and s2 will always be of length 1 or higher. How can I speed this up? ``` int l1 = s1.length(); if (l1 > 3) { l1 = 3; } if (s2.startsWith(s1.substring(0,l1))) { // do something.. } ``` Regex maybe?