I have the following code in an equals method.
public boolean equals(Object o){
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof Vertex)) return false;
return ((Vertex) o).label().equals(label);
}
My IDE highlights the if statement and wants me to basically do this
public boolean equals(Object o){
return (o != null) && ((o==this) || ((o instanceof Vertex) && ((Vertex) o).label().equals(label);
}
I’ve been told that the compiler is generally smart enough to optimize and that in general one should code for readability. So, clearly the second code sample is not as easy to read as the first. Is my IDE just being annoying or is there some actual performance merit to doing it that way?
First, only optimize if you know it’s a bottleneck, else code for readability.
You can check the byte code to see but I suspect they are pretty close if not exactly the same. Even if there are slight differences in bytecode, I’ve seen the JIT compiler optimize stuff down to where there is no difference. You can always do performance tests to be sure.