Skip to content
Advertisement

Why is list.size()>0 slower than list.isEmpty() in Java?

Why is list.size()>0 slower than list.isEmpty() in Java? On other words why isEmpty() is preferable over size()>0?

When I look at the implementation in ArrayList, then it looks like the speed should be the same:

ArrayList.size()

JavaScript

ArrayList.isEmpty()

JavaScript

If we just write a simple program to get the time take by both the methods, that case size() will take more isEmpty() in all cases, why this so?

Here is my TestCode;

JavaScript

Here eTime-sTime>eeTime-eTime in all cases. Why?

Advertisement

Answer

Your testing code is flawed.

Just reverse the order, i.e call isEmpty first and size > 0 second and you’ll get the opposite result. This is due to class loading, caching, etc.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement