Appreciate if you could explain the performance efficiency of the following 2 methods to check the emptiness of List in Java.
- {list}.size() == 0
- {list}.isEmpty()
Appreciate if you could explain the performance efficiency of the following 2 methods to check the emptiness of List in Java.
For common list implementations, they're exactly the same. Looking at the source code of OpenJDK's ArrayList
, the implementation of isEmpty()
is as follows:
public boolean isEmpty() {
return size == 0;
}
And the implementation of size()
:
public int size() {
return size;
}
In general, this type of nano-optimization is almost never worth caring about. If a more readable standard method is available, use it.
When in doubt, check the Javadoc, the source code of the JDK you're using, or perform a micro-benchmark.