FindBugs警告:使用keySet迭代器而不是entrySet迭代器效率低下 [英] FindBugs warning: Inefficient use of keySet iterator instead of entrySet iterator

查看:3952
本文介绍了FindBugs警告:使用keySet迭代器而不是entrySet迭代器效率低下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考以下方法:

public Set<LIMSGridCell> getCellsInColumn(String columnIndex){
    Map<String,LIMSGridCell> cellsMap = getCellsMap();
    Set<LIMSGridCell> cells = new HashSet<LIMSGridCell>();
    Set<String> keySet = cellsMap.keySet();
    for(String key: keySet){
      if(key.startsWith(columnIndex)){
        cells.add(cellsMap.get(key));
      }
    }
    return cells;
  }

FindBugs给出了这条警告信息:

FindBugs give this waring message :


低效使用keySet迭代器而不是entrySet迭代器
此方法使用$ b键访问Map条目的值从keySet迭代器中检索$ b。在map的entrySet上使用
迭代器更有效,以避免Map.get(key)
查找。

"Inefficient use of keySet iterator instead of entrySet iterator This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup."


推荐答案

您正在检索所有密钥(访问整个地图),然后对于某些密钥,您再次访问地图获得价值。

You are retrieving all the keys (accessing the whole map) and then for some keys, you access the map again to get the value.

您可以遍历地图以获取地图条目( Map.Entry )(一对键和值)并且只访问一次地图。

You can iterate over the map to get map entries (Map.Entry) (couples of keys and values) and access the map only once.

地图.entrySet()使用密钥和相应的值提供一组 Map.Entry

Map.entrySet() delivers a set of Map.Entrys each one with the key and corresponding value.

for ( Map.Entry< String, LIMSGridCell > entry : cellsMap.entrySet() ) {
    if ( entry.getKey().startsWith( columnIndex ) ) {
        cells.add( entry.getValue() );
    }
}

注意:我怀疑这将是一个很大的改进,因为如果你使用地图条目,你将为每个条目实例化一个对象。我不知道这是否真的比调用 get()更快,并直接检索所需的引用。

Note: I doubt that this will be much of an improvement since if you use map entries you will instantiate an object for each entry. I don't know if this is really faster than calling get() and retrieving the needed reference directly.

这篇关于FindBugs警告:使用keySet迭代器而不是entrySet迭代器效率低下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆