简体   繁体   English

在进入(Iterator.hasNext())循环之前,Map.isEmpty()是否有意义?

[英]Does Map.isEmpty() make sense before entering while (Iterator.hasNext()) loop?

In the following code snippet, does the check for dic.isEmpty() result in any performance improvement? 在下面的代码片段中,对dic.isEmpty()的检查是否会带来任何性能改进?

    for (Map<String, String> dic : dics) {
      if (!dic.isEmpty()) { 
        Iterator<Map.Entry<String, String>> it = dic.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pair = it.next();
            Log.d("Substitute", pair.getKey() + " => " + pair.getValue());
        }
      }
    }

After all, if the map/dic is empty, the while() loop will not be entered, so it looks like the check for dic.isEmpty() is redundant - unless there is some other justification for it? 毕竟,如果map / dic为空,则不会输入while()循环,因此看起来对dic.isEmpty()的检查是多余的-除非有其他理由?

It is redundant. 这是多余的。 I'd say, leave it out. 我会说,把它排除在外。 This smells premature micro-optimization. 这闻到了过早的微优化。

Since the empty map should not be treated as a special case in this scenario, the isEmpty just clutters the code imo. 由于在这种情况下不应将空映射视为特殊情况,因此isEmpty只会使代码imo混乱。

It is an attempt to prematurely optimize the code. 这是过早优化代码的尝试。

Your Map is either always going to be empty or not empty: 您的地图要么总是为空,要么为空:

  1. If it is empty, then returning back a "no item" iterator is likely to return back the same static "empty iterator" (Collections.EmptyIterator) so the impact on memory is negligable. 如果为空,则返回“无项目”迭代器很可能会返回相同的静态“空迭代器”(Collections.EmptyIterator),因此对内存的影响可以忽略不计。

  2. If it is full, then the check is just going to slow down the access to the needed iterator. 如果已满,则检查只会减慢对所需迭代器的访问。

The main issue is that it could incur race conditions, if another thread adds items between the check for empty and the grab of the iterator. 主要问题是,如果另一个线程在检查是否为空和抓取迭代器之间添加了项,则可能会导致竞争状况。 That said, it's likely that the cost of returning a null iterator is negligible (many tuned collections return back a singleton null iterator), so the extra check is overkill. 就是说,返回null迭代器的成本可能微不足道(许多调整后的集合返回了singleton null迭代器),所以额外的检查是过分的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM