Skip to main content

String.compareTo(String anotherString)

1 reply [Last post]
jcmeira
Offline
Joined: 2003-08-02
Points: 0

I think that the firts line in the method "String.compareTo(String anotherString)" could be

if(anotherString==this) return 0;

because if the two Strings are the same, the method make
innecesary operations.

public class TestStringEquals {

public TestStringEquals(){}

public static void main(String[] args) {
String orig="HELLO WORLD";
String cop=orig;
long ini=System.currentTimeMillis();
int k=0;
for(int i=0;i<100000000;i++){
boolean b=(orig.compareTo(cop)==0);
b=orig==cop;
if(b) k++;
}
long fin=System.currentTimeMillis();
System.out.println("Time I="+(fin-ini));

ini=System.currentTimeMillis();
k=0;
for(int i=0;i<100000000;i++){
boolean b=compareTo(orig,cop)==0;
if(b) k++;
}
fin=System.currentTimeMillis();
System.out.println("Time II="+(fin-ini));
}

public static int compareTo(String s1,String s2){
if(s1==s2) return 0;
return s1.compareTo(s2);
}
}
.............

Time I=2687
Time II=438

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
sjasja
Offline
Joined: 2004-08-15
Points: 0

The microbenchmark above is a bit dodgy as it measures not only run time but also Hotspot compilation time. A really smart compiler could also compile it to nothing because the final value of "k" is never used, hence assignments to it can be optimized away, and so the string comparisons can be optimized away, and then the loops can be optimized away (though in this particular program I think Hotspot doesn't optimize everything away at the moment.)

If you care about performance you should be running with "java -server" which gives very different times.

As far as I can figure out Hotspot doesn't really use the Java version of compareTo(), it uses hand-optimized assembly.

Even with all that, yes, the "==" comparison speeds up identical string comparisons. The trouble is it slows down every other string comparison, since the "==" check is executed for every string comparison.

So the question becomes: in real programs (not artificial microbenchmarks), what percentage of String.compareTo calls really compare the exact same objects? A small percentage makes the extra check hurt more than help.

If you are really interested in this: instrument compareTo() so that it collects statistics on same vs different objects. Note the hand-optimized assembly thing; you'll have to get around that. Then run a suitably wide collection of real applications with real user load and post the statistics.