https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

statmark56

11/10/2023, 3:25 PM
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

Jacob

11/10/2023, 3:49 PM
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

Johann Pardanaud

11/10/2023, 3:51 PM
use asList to use the original array
k

Klitos Kyriacou

11/10/2023, 4:03 PM
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

Johann Pardanaud

11/10/2023, 4:04 PM
oh you're right, sorry for the misleading answer!
what about asIterable?
k

Klitos Kyriacou

11/10/2023, 4:06 PM
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

Johann Pardanaud

11/10/2023, 4:08 PM
right, I really didn't help there, sorry 😅
s

statmark56

11/10/2023, 4:13 PM
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

Wout Werkman

11/10/2023, 4:19 PM
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

Jacob

11/10/2023, 4:20 PM
Yeah I’m changing my answer No allocations until toList is called which will allocate N references. not 2N
e

ephemient

11/10/2023, 4:51 PM
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

ilya.gorbunov

11/12/2023, 12:41 AM
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

Klitos Kyriacou

11/12/2023, 3:03 PM
Good point, Ilya, thanks.