Understanding the differences between Collection.isEmpty () and Collection.size () == 0?

I read as many articles as the difference between isEmpty() and size() > 0 to check that collection empty or not, and found that isEmpty() has performance over size() , but I could not easily understand why performance isEmpty() is good, although inside isEmpty () only size == 0?

My questions are :

  • Can someone explain in which scenario isEmpty() is faster, and also when to use the function isEmpty() and size() to check if the collection empty or not?

  • Can someone explain this using code or another way (charts, graphs, etc.) so that any beginner can easily understand?

+6
source share
3 answers

Maybe some collections just use size()==0 inside their isEmpty() method, but that doesn't mean they all do. The default implementation isEmpty() by default checks to see if size() == 0 , but a particular collection can override this with something else if it is more efficient.

Here is a good example. The ConcurrentSkipListSet documentation says:

Beware that, unlike most collections, the size method is not a constant time operation.

For this class, you certainly want to use isEmpty() , not size() == 0 .

(To understand why this is true for the skip list, you will need to find out how the skip lists work, but go back and ask another question about them if you want to know more.)

+6
source

Basically, I found that .size() can be O (1) or O (N) , depending on the data structure ; .isEmpty() never O (N) .

+3
source

The main reasons for using isEmpty rather than size will be the following:

 it is more expressive (the code is easier to read and to maintain) it is faster, in some cases by orders of magnitude. 

Detailed explanation here

++ the same question is asked here

+1
source

Source: https://habr.com/ru/post/979777/


All Articles