对于集合一定要调用isEmpty
来源:互联网 发布:飞思卡尔单片机怎么学 编辑:程序博客网 时间:2024/05/18 19:46
对于集合一定要调用isEmpty
目录(?)[+]
Reasons to call.isEmpty on collections
我已经不止一次看到这样的代码:
if (collection.size() > 0) { ...}
这是大多数程序员检查集合不为空的第一固有想法。但是,这里有一个更好的方法isEmpty:
if (!collection.isEmpty()) { ... }
使用isEmpty而不是size有以下几个原因:
l 它更有易懂(非常容易维护和阅读)
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
- 对于集合一定要调用isEmpty
- 对于集合一定要调用isEmpty
- isEmpty()
- IsEmpty
- 对于集合的选择
- Arraylist 调用 isempty 与size抛出空指针异常
- java 对于集合的排序
- 对于list集合的认知
- 对于UVa12096“集合的集合”的理解
- viewDidAppear中一定要调用[super viewDidAppear]
- 为什么requestWindowFeature一定要在setContentView之前调用?
- RadioButtonList1对于数据库的调用
- 对于递归调用的理解
- 对于类的调用方法
- 判断一个list集合是否为空,用isEmpty 还是 null的问题???
- 调用layoutSubviews一定要注意别忘了调用父类
- spring对于集合类型的装配
- 对于java中的集合的排序
- C++ 快速幂取模+大数相乘取模
- LeetCode Word Break
- WEB前端试题收集
- 负载均衡,程序猿必备的知识储备
- Android项目重构之路:架构篇
- 对于集合一定要调用isEmpty
- 安装memcached
- Shell脚本学习笔记-条件判断
- Android性能专项测试测试点指导(一)
- java对字符串操作大全
- 唯爱小粽子:软件架构的典型组成部分-性能
- CF 665E 限制异或和的区间计数
- bzoj 1060: [ZJOI2007]时态同步(树形DP)
- flume源码分析--Log4j日志直接发送到Flume过程分析(二)