Dart:我是否应该遍历Map.entries或Map.values? [英] Dart: Should I prefer to iterate over Map.entries or Map.values?

查看:99
本文介绍了Dart:我是否应该遍历Map.entries或Map.values?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我需要遍历Dart中的 Map 的值时,我都会考虑此循环将产生的成本,包括复杂性和产生的垃圾量.有两种方法可以迭代 Map 的值: Map.values Map.entries .例如:

Every time I need to iterate over the values of a Map in Dart, I contemplate the cost that this loop will incur, in terms of the complexity and the amount of garbage produced. There are two ways to iterate over the values of a Map: Map.values, and Map.entries. For example:

Map<String, Person> people;

int olderThan(int age) {
  int result = 0;
  for(Person p in people.values)
    if(p.age > age) result++;
  return result;
}

int olderThan2(int age) {
  int result = 0;
  for(MapEntry<String, Person> me in people.entries)
    if(me.value.age > age) result++;
  return result;
}

// Which one is faster: olderThan or olderThan2?

如果 Map 在内部将其值存储为 MapEntry 对象,则 entries 可能与效率相同甚至更高.>值. Map 的实现细节被深埋在Dart库的内部,所以我想知道是否有人知道这些知识并且可以阐明这一主题.

If Map stores its values internally as MapEntry objects, it's possible that entries would be just as efficient or even more efficient than values. The implementation details of Map are buried deep inside Dart libraries, so I wonder if anybody has this knowledge and can shed the light on this subject.

我了解到 Map.entries 使您可以访问密钥,但是我所谈论的是不需要使用条目密钥的情况.我也了解 Map 有不同的实现.我对默认实现 LinkedHashMap 最为感兴趣,但是,很高兴知道在这方面不同的 Map 实现之间是否有区别.

I understand that Map.entries gives you access to the key, but I am talking about cases where I don't need to use the key of the entry. I also understand that there are different implementations of Map. I am mostly interested in the default implementation, LinkedHashMap, but if it would be nice to know if there's a difference between the different Map implementations in this aspect.

推荐答案

如果迭代条目,则会为每个键值组合创建 MapEntry 实例.

If you iterate over entries a MapEntry instance is created for every key-value combination.

如果只需要值,则迭代 map.values 效率更高.

If you only need values, iterating map.values is more efficient.

这篇关于Dart:我是否应该遍历Map.entries或Map.values?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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