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.
We should iterate map based on the requirement.
If we required to iterate only keys
map.keys.forEach((k) => print("Key : $k"));
If we required to iterate only values
map.values.forEach((v) => print("Value: $v"));
If we required to iterate both key values.
map.forEach((k, v) => print("Key : $k, Value : $v"));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With