Hello everyone, I'm trying to understand if there ...
# general-advice
j
Hello everyone, I'm trying to understand if there is a difference between
Map.entries.forEach
and
Map.forEach
Calling entries can be expensive, not sure if second example does the same behind?
c
Yes, both of these lines are the same after compilation. From the stdlib:
Copy code
@kotlin.internal.InlineOnly
public inline operator fun <K, V> Map<out K, V>.iterator(): Iterator<Map.Entry<K, V>> = entries.iterator()
What makes you think using
entries
is expensive? It's a two object allocations (instead of one for any other iterator), and it's cached between calls for the Java HashMap. Except in very rare cases, it's virtually free.
j
Full disclosure, I got this feedback from my coworker, so unfortunately I can't argue you here 🙂 Thanks for the answer btw