Mutable lists reduce the amount of memory needed?

Chapter: Mutable vs. Immutable
...Section: Mutable lists reduce the amount of memory needed?

When we program with immutable lists, we do throw away a lot of nodes. A node is "thrown away" when there are no references to it remaining in your program. For example in the sequence:

Node foo = new Node(14, null);   // line 1
...
foo = new Node(42, null);        // line 2
At line 1 memory is allocated sufficient to hold a Node's data. At line 2, the only reference to that section of memory is changed to refer to a completely different section of memory. That first section is, in this sense, thrown away. It can be referred to as "garbage" since there is no way for our program to access it any more.

This certainly seems wasteful. If foo were a MutableNode, we could replace line 2 by

foo.setData(42);

foo would still refer to the originally allocated section of memory. Only now we would have changed the data in that section.

It's true: The Immutable style does result in more allocation of memory. On the other hand, modern programming languages like Java guarantee that the "garbage" -- the previously allocated, but no longer needed, memory -- will be automatically returned to be available again for re-use later in the program's run. Java has a "garbage collector" thread that automatically runs all the time your program is running.

Decades ago, when allocation and deallocation of dynamic memory had to be explicitly coded for by the programmer, human oversight often led to the creation of garbage that was never deallocated. This caused a program's memory requirements to bloat. Programmers would refer to "memory leaks". Such programs would run ok for a while, but then start to slow down and eventually crash as memory demands led to paging, then thrashing, then eventually crashing.

Most humans are not very good at deallocating memory when it is no longer needed. Hence the need for garbage collector threads. Overall, because of the need for some little time for the garbage collector to do its work, code for immutable lists will probably run a very tiny bit slower than well-written equivalent code for mutable lists.

On the other hand, it can be argued (and I would so argue) that it is more difficult to create well-written code in the mutable paradigm than it is in the immutable. It's an error-prone field. What is your experience so far in this lab? Was the immutable Ex 3 easier than the mutable Ex 4?


rhyspj@gwu.edu