Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala List.updated

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)
like image 239
user592419 Avatar asked Dec 06 '22 18:12

user592419


1 Answers

  1. 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.

  2. Changing an element in an ArrayBuffer has constant time and memory complexity. The backing array is updated in place, no copying occurs.

  3. 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.

like image 111
Jean-Philippe Pellet Avatar answered Dec 24 '22 11:12

Jean-Philippe Pellet