Why is list.size()>0 slower than list.isEmpty() in Java? On other words why isEmpty() is preferable over size()>0?<
It is impossible to say in general which is faster, because it depends on which implementation of interface List you are using.
Suppose we're talking about ArrayList. Lookup the source code of ArrayList, you can find it in the file src.zip in your JDK installation directory. The source code of the methods isEmpty and size looks as follows (Sun JDK 1.6 update 16 for Windows):
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
You can easily see that both expressions isEmpty() and size() == 0 will come down to exactly the same statements, so one is certainly not faster than the other.
If you're interested in how it works for other implementations of interface List, look up the source code yourself and find out.