对于集合一定要调用isEmpty

来源:互联网 发布:飞思卡尔单片机怎么学 编辑:程序博客网 时间:2024/05/18 19:46
 

对于集合一定要调用isEmpty

标签: collections测试jdk
 2188人阅读 评论(0) 收藏 举报
 分类:
 
 

目录(?)[+]

 Reasons to call.isEmpty on collections

我已经不止一次看到这样的代码:

if (collection.size() > 0) { ...}

这是大多数程序员检查集合不为空的第一固有想法。但是,这里有一个更好的方法isEmpty:

if (!collection.isEmpty()) { ... }

使用isEmpty而不是size有以下几个原因:

它更有易懂(非常容易维护和阅读)

l  它速度更快,在大量数据的情况下。从JDK可以得到两个显而意知的例子ConcurrentLinkedQueue和NavigableMap/NavigableSet。所有这些size实现都是通过迭代集合得到,因为这样,随着元素数量增加,调用size()变得越来越慢。

Todays source code做了一个对比性能测试,分别对小(10个元素)和大(1000000个元素)的集合调用size和 isEmpty方法进行了测试。尽管基准测试特别是微基准测试需要大量的调用,但是这些结果表明,调用size()对于不同大小的集合至少有10倍以上的时间差别,而isEmpty只有很小的差别.

I’ve seen many times code like the one below:

 if (collection.size() > 0) { ...}

 

There is just something which inherently “clicks” with most programmersminds when they think “non-empty”. There is however a method which is moreappropriate in most of the cases: isEmpty:

if (!collection.isEmpty()) { ... }

The top reasons for using isEmpty rather than size would be:

  • it is more expressive (the code is easier to read and to maintain)
  • it is faster, in some cases by orders of magnitude. Two examples from the JDK where this is extremely visible would be theConcurrentLinkedQueue and NavigableMap / NavigableSet. All of these implement the “size” method by iterating trough the collection and because of this, calling size gets increasingly slower as the number of elements increase

Todays source code performs a comparativebenchmark between small (10 element) and large (1 000 000 elements) collectionsby timing the calls to the size and is empty methods. While benchmarks andespecially micro-benchmarks needs be taken with a large grain of salt , these tests show that thereis at least a factor of 10x difference in time when calling the size method andthere is very little difference when calling the isEmpty method.

 

From http://www.transylvania-jug.org/archives/140

 


0
0
0 0
原创粉丝点击