-2

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()
  • 4
    There is no difference. This is not worth caring about. – Louis Wasserman Jul 29 '22 at 01:06
  • 5
    Actually, in the general case there **can be** a performance difference. But you need to look at the specific `List` implementation to understand what it will be. (For the standard `ArrayList` and `LinkedList` there is no difference.) – Stephen C Jul 29 '22 at 01:31
  • 3
    There is a general principle: don't optimize things unless you *know* that optimization is necessary. And they only real what to know that (accurately) is to benchmark and profile *at the application level* ... before you start optimizing. Then just optimize the hotspots. Beware of premature optimization. It is a waste of time and effort. – Stephen C Jul 29 '22 at 01:35
  • 2
    There are only two possible scenarios 1) implementations where `isEmpty()` as just the same as `size() == 0` (where the current size is stored in a field) and 2) implementations where `size()` has to perform an actual, potentially expensive counting operation but `isEmpty()` can be much cheaper, as the actual count is not needed. In general, there is no reason not to use `isEmpty()` when you want to know whether a collections *is empty*. – Holger Jul 30 '22 at 10:46

1 Answers1

3

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • 3
    `ArrayList` is just one implementation. A counter-example would be `ConcurrentSkipListMap`… – Holger Jul 30 '22 at 10:54