I have: ```val map: Map<Int, String> = ... ``` If ...
# getting-started
s
I have:
Copy code
val map: Map<Int, String> = ...
If I create a list via:
Copy code
val list: List<String> = map.values.toList()
Will I cause memory allocation: 2*N, where N = size of String entries (1 from map, 1 from the list)?
j
I’m guessing: The actual strings will only be in memory once There will already be N references to the strings before you call values.toList() There will be at least 2N References when the call completes. There will be up to 3N references during the calls but the intermediate list will eventually get garbage collected So short answer. Yes, 2N but 2N references, not 2n Strings Disclaimer. I’m just making a mildly educated guess
1
j
use asList to use the original array
k
That could be nice, but
map.values
is a collection. There's no technical reason
asList
couldn't exist for a collection, but it doesn't. It's only defined for arrays.
j
oh you're right, sorry for the misleading answer!
what about asIterable?
k
map.values
is a Collection, which is already an
Iterable
. The main point for the OP is don't call
toList()
unless you absolutely need a
List
.
j
right, I really didn't help there, sorry 😅
s
Thanks guys. Completely agree with @Jacob for 2N -> references, not actual object allocation. Now, will the number of references ever cause OutOfMemoryException in jvm?
w
This depends on the implementation of
Map
.
Map.values
will most likely be implemented as a view. So it will most likely have allocations independent of
N
.
.toList()
will always introduce at least
N
, and most likely not more
j
Yeah I’m changing my answer No allocations until toList is called which will allocate N references. not 2N
e
allocates a list object with a backing array of size N for. not sure what you mean by "allocate N references", that's kind of odd phrasing since references aren't what's being allocated
i
That could be nice, but map.values is a collection. There's no technical reason
asList
couldn't exist for a collection,
@Klitos Kyriacou For example, one reason is that
List
requires implementing indexed access to elements and reverse iteration and
Collection
doesn't provide these.
👍 1
k
Good point, Ilya, thanks.