Code 1:
private static int myCompare(String a, String b) {
/* my version of the compareTo method from the String Java class */
int len1 = a.length();
int len2 = b.length();
if (len1 == len2) {
for (int i = 0; i < a.length(); i++) {
int intValueOfStringA = (int) a.charAt(i);
int intValueOfStringB = (int) b.charAt(i);
if (intValueOfStringA != intValueOfStringB) {
return intValueOfStringA - intValueOfStringB;
}
}
}
return len1 - len2;
}
Code 2:
private static int stringCompare(String a, String b) {
/* Direct implementation of the compareTo from the String Java class */
int len1 = a.length();
int len2 = b.length();
int lim = Math.min(len1, len2);
char[] v1 = a.toCharArray();
char[] v2 = b.toCharArray();
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
Please ignore commenting on the type of access modifier used or the args made available to the method. I actually came up with Code 1 before being counseled by my friend to use the "compareTo" method from the String Class, which is reproduced here under Code 2. I wonder which piece of code is more effective though (w.r.t time and memory). Please advise.
I am trying to understand the Big O for both the code blocks and trying to elegantly improve efficiency. IMO Code 2 is relatively costly w.r.t memory usage. I want to confirm this. I apologize if my question is possibly alluding to the classic micro-optimization Vs. readable code debate.