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

后端 未结 9 1933
误落风尘
误落风尘 2020-12-13 03:58

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

9条回答
  •  长情又很酷
    2020-12-13 04:23

    Given those two implementations, the speed should be the same, that much is true.

    But those are by far not the only possible implementations for these methods. A primitive linked list (one that doesn't store the size separately) for example could answer isEmpty() much faster than a size() call.

    More importantly: isEmpty() describes your intent exactly, while size()==0 is unnecessarily complex (not hugely complex of course, but any unnecessary complexity at all should be avoided).

提交回复
热议问题