I am curious about List.updated. What is it's runtime? And how does it compare to just changing one element in an ArrayBuffer? In the background, how does it deal with copying all of the list? Is this an O(n) procedure? If so, is there an immutable data structure that has an updated like method without being so slow?
An example is:
val list = List(1,2,3)
val list2 = list.updated(2, 5) --> # list2 = (1,5,3)
var abuf = ArrayBuffer(1,2,3)
abuf(2) = 5 --> # abuf = (1,5,3)
The time and memory complexity of the updated(index, value)
method is linear in terms of index
(not in terms of the size of the list). The first index
cells are recreated.
Changing an element in an ArrayBuffer
has constant time and memory complexity. The backing array is updated in place, no copying occurs.
This updated
method is not slow if you update elements near the beginning of the list. For larger sequences, Vector
has a different way to share common parts of the list and will probably do less copying.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With