Http://blog.csdn.net/chenhui1219/article/details/5628843#comments
Java compares two strings to improve code running efficiency:
In programming, sometimes we need to compare strings cyclically. The common method is equals as follows:
Public class testequals extends thread {
Public static void main (string ARGs []) {
String [] checkstr = {"", "aaaa", "BBBB", "SDF", "dsdf "};
String STR = "Dingdong ";
For (INT I = 0; I <checkstr. length; I ++ ){
If (Str. Equals (checkstr [I]) {// compare string
System. Out. println ("Dingdong has in the checkstr list! ");
Break;
}
}
}
}
The source code of equals is as follows:
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;
While (n --! = 0 ){
If (V1 [I ++]! = V2 [J ++])
Return false;
}
Return true;
}
}
Return false;
}
We can see that to get the same string, you must perform the following operations: 1) compare whether it is the same object: "If (this = anobject) {"; 2) whether it is the same type object: "If (anobject instanceof string) {"; 3) convert the string to determine whether the string length is the same: "If (n = anotherstring. count) {"; 4) Split strings for one-to-one comparison. Return a Boolean value.
Through the above analysis, the string is compared with the result value after the 4-complement operation.
When we know that the two objects to be compared are strings, We can optimize the code! The optimized result is as follows:
Public static void main (string ARGs []) {
String [] checkstr = {"", "aaaa", "BBBB", "SDF", "dsdf "};
String STR = "Dingdong ";
Int strl = Str. Length ();
For (INT I = 0; I <checkstr. length; I ++ ){
If (checkstr [I]! = NULL & strl = checkstr [I]. Length () {// first judge the length, reduce the number of calls to the equals method directly
If (Str. Equals (checkstr [I]) {// compare string
System. Out. println ("Dingdong has in the checkstr list! ");
Break;
}
}
}
}
When the string array we need to compare is very large, for example, there are thousands of string [1000] objects, and each string object is relatively long, its performance will be more obvious.
Method to avoid repeated use of the equals method.