Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I prefer to iterate over Map.entries or Map.values?

Tags:

dart

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?

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.

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.

like image 552
Alexander Ryzhov Avatar asked Feb 15 '19 18:02

Alexander Ryzhov


2 Answers

We should iterate map based on the requirement.

  1. If we required to iterate only keys

    map.keys.forEach((k) => print("Key : $k"));

  2. If we required to iterate only values

    map.values.forEach((v) => print("Value: $v"));

  3. If we required to iterate both key values.

    map.forEach((k, v) => print("Key : $k, Value : $v"));

like image 113
Jitesh Mohite Avatar answered Oct 14 '22 09:10

Jitesh Mohite


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

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

like image 24
Günter Zöchbauer Avatar answered Oct 14 '22 10:10

Günter Zöchbauer