Some claim that appending to immutable lists is more efficient. Is this true? How?
Some claim that appending to immutable lists is more efficient. Is this true? How?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Producing a modified version of a list by allocating an array large enough to hold the modified version and copying over all of the unmodified elements is somewhat expensive, regardless of whether the modification is an append, an insert, a deletion, replacement, or anything else. The cost is roughly comparable to that of producing an unmodified, but distinct, copy of the list.
If an object
Foowishes to maintain a list of elements in such a way that it can only be changed whenFoochanges it, there are two common approaches it can use to do so:If one uses approach #1, then every time
Fooalters the list it must create a new “immutable list” instance, butFoocould answer a request for the list’s contents without having to copy it. If one uses approach #2, adding items to the list (and other modifications) will be cheaper, but answering a request for the list’s contents will require copying the list. Whether it’s better to use approach #1 or approach #2 will depend upon how often the list is updated, versus how often the application will need a copy of it.