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 ofindex(not in terms of the size of the list). The firstindexcells are recreated.Changing an element in an
ArrayBufferhas constant time and memory complexity. The backing array is updated in place, no copying occurs.This
updatedmethod is not slow if you update elements near the beginning of the list. For larger sequences,Vectorhas a different way to share common parts of the list and will probably do less copying.