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.