How does memory management work for Scala collections?

I cannot understand the implementation of some operations for Scala immutable sequences. I will use this as an example:

def example: List[Int] = { val list0 = List.range(1,10) list0.tail } 

As soon as the function finishes executing list0, it is now out of scope. Will the head of list0 be deleted from memory, or will the list remain unchanged until the entire list is garbage collected?

+5
source share
2 answers

In your example, the head of list0 will be left to the garbage collector to collect, since nothing will refer to it. However, the remaining elements (tail) will continue to exist after exiting the function (if the result of the call is assigned to something).

Each cell in the list maintains a link to the next cell in the list (or to Nil ), but not vice versa.

+6
source

You create a total of 12 (possible) objects

  • list0 is a list containing from 1 to 10.
  • 10 individual elements ranging from 1 to 10. They can be interned, but that's another discussion.
  • The return value is list0.tail , which contains elements 2-10.

Here is a graph of conceptual memory immediately before the last brace, here are the links

  Somewhere on JVM Stack list0(head)->1->2 ... ->10 | Top of JVM Stack, contains returnList with head->| 

When the function is executed, the list0 link will be deleted and will have the right to garbage collection. Since list0 is the only thing referenced 1 , 1 is an honest game to collect garbage.

Elements 2-10, as well as the returned list containing them, will remain on the heap, since everyone who refers to example still accessible by executable code.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1232318/


All Articles