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

后端 未结 9 1894
误落风尘
误落风尘 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:25

    .size() has to look at the entire list, while .isEmpty() can stop at the first one.

    Obviously implementation dependent, but as has been said before, if you don't need to know the actual size, why bother counting all the elements?

    0 讨论(0)
  • 2020-12-13 04:25

    You said:

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

    First off, it's probably because of your testing code. You can't test the speed of calling l.size() and l.isEmpty() at the same time, since they both query the same value. Most likely calling l.size() has loaded the size of your list into your cpu cache and calling l.isEmpty() is a lot faster as a result.

    You could try calling l.size() a couple of million times and l.isEmpty() a couple of million times in two separate programs but in theory the compiler could just optimize away all those calls since you're not actually doing anything with the results.

    In any case, the performance difference between the two will be negligible, especially once you do the comparison you need to do to see if the list is empty (l.size() == 0). Most likely the generated code will look almost completely similar. As some other posters noted, you want to optimize for readability in this case, not speed.

    edit: I tested it myself. It's pretty much a toss-up. size() and isEmpty() used on Vector gave differing results on long runs, neither beat the other consistently. When run on an ArrayList size() seemed faster, but not by much. This is most likely due to the fact that access to Vector is synchronized, so what you're really seeing when trying to benchmark access to these methods is synchronisation overhead, which can be very sensitive.

    The thing to take away here is that when you're trying to optimize a method call with a couple nanoseconds difference in execution time, then you're doing it wrong. Get the basics right first, like using Longs where you should be using long.

    0 讨论(0)
  • 2020-12-13 04:27

    Counting items in a linked list can be very slow.

    0 讨论(0)
提交回复
热议问题