I looked at the source of java.lang.String and noticed that the equals method does not check if char[] supports every line is the same object. Wouldn't that improve the comparison time?
The alleged improvement contained in this rewritten version is:
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; if(v1==v2 && i==j){ return true; } while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return false; }
I believe that this will improve performance if two strings were obtained using String.substring and possibly even interned strings.
Does anyone know if there is a reason why they decided not to implement it this way?
Update: For those who may not know much about string implementation , there are times when other than the String pool, where two String objects can have the same char [] value, int offset and int count.
Consider the following code:
String x = "I am a String, yo!"; String y = x.split(" ")[3]; String z = x.substring(7,14);
You will have this situation: 
It is also obvious that the Strings value-sharing function was eliminated in Java 7u6 to satisfy some benchmarks. Therefore, if you took the time to make your code work at a decent time (or in general) using String.substring () rather than String concatenation, you are SOL.
source share