Answer the question
In order to leave comments, you need to log in
Why is immutable good?
When you read smart books on functional programming (in my case it was a book on Scala), they write everywhere that immutable is good. It seems that the result is obvious: the problem with multithreading and the side effect that mutable can lead to disappears by itself. But this approach also has its drawbacks (as I understand it).
For example, there is a task to add 1000 elements to an array, but there are no 100,000 elements. A true-fp programmer will say that immutable is good and we need to create a new array every time we add it, which consists of the elements of the old +1 (which is successfully implemented at the PL level, in the second case of Scala). Is this approach justified in terms of resources (memory in this case)? After all, the task is simple, to add elements to the array, for which we have the creation of 100,000 instances of the array. Yes, I understand that there is a GC that will clean up after us, but creating such a rather complex data structure as an array (meaning List) will take quite a lot of time.
What do you say to that?
Answer the question
In order to leave comments, you need to log in
Among other things, in my opinion - things that change are always additional complexity and a source of defects. Thus, immutable allows you to reduce the above risks, sometimes at the cost of resources.
Let's say there is a class in which there is some field that is set when an instance of this class is created, and by reading the code - we can be 100% sure that this field will retain its value under any conditions for this instance and we will not need to look for something else could happen to him. Again, you don't have to bother with getters and created a public immutable variable - and the data is immediately protected from writing from outside.
As for immutable arrays, there are none in Scala.
There is an immutable List. This List is designed to add and remove elements at the beginning of the list - head. And if you map or filter a list, the new list is formed in the same "optimal" order.
In this case, there is no memory overhead and GC load compared to Java LinkedList: when an element is added, a NEW List object is created with a link to the new element (head) and a link to the old list (tail). Old sheets in action. Each new sheet is an object of just two references.
Is this approach justified in terms of resources (memory in this case)?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question