1

Is there a new comparison made everytime compareTo is called in the same if - else if construct or is there a single comparison made?

public void genericComparisons(Comparable e, Comparable target){
    if(e.compareTo(target) == 0)
       // do this
    else if(e.compareTo(target) > 0)
       // do something else
    else if(e.compareTo(target) < 0)
       // do that
} // end method
imnotmarvin
  • 55
  • 1
  • 7
  • 1
    Java has a feature called “local variables”. Just call `e.compareTo(target)` once and store the result into a local `int` variable. – Holger Sep 27 '14 at 20:30

1 Answers1

0

You can obviously optimize it using a local variable... and such an optimization is always good as it makes you code clearer and less repetitive.

However, assuming you compareTo is a simple side-effect free method, the JVM will probably inline it and can do this optimization for you. I guess, this is what you actually wanted to know.

There's no easy way to find it out, especially using println must fail, as the JVM is allowed to make you program faster, but not behaving differently. You can't see it in the bytecode, as this contains no optimizations at all, they happen when the programs runs for a while.

The JVM is also not allowed to improve you coding style, so I'd suggest to use local variables, especially for more complicated expressions.


Your last condition is obviously always true, when reached. If you want the code to look systematically and symmetrically, use this

public void genericComparisons(Comparable e, Comparable target) {
    int cmp = e.compareTo(target);
    if (cmp < 0) {
       // less
    } else if (cmp > 0) {
       // greater
    } else {
       // same
    }
}
maaartinus
  • 44,714
  • 32
  • 161
  • 320