2

i have a question about Structural sharing from List in Scala. I have read some where in the Internet this sentence

List implements structural sharing of the tail list. This means that many operations are either zero- or constant-memory cost.

but i dont really understand how would time and memory cost of the operations for lists be reduced. For example

val mainList = List(3, 2, 1)
val with4 =    4 :: mainList // O(1)

if we want to create another list with4 time would just be O(1) and memory cost one instead but for operations of the list how would it be different ? I mean with length() or reverse() ... it would still be O(n) as normal ? Can anyone please explain me and if you can maybe an example would be really helpful. Thank you!

1 Answers1

2

The operations on list that run in constant time (O(1)) due to structural sharing are prepend (::), head, and tail. Most other operations are linear time (O(n)).

You example is correct 4 :: myList is constant time, as are myList.head and mylist.tail, other things like length and reverse are linear time.

This is why List is not a particularly good collection to use in most cases unless you only use those operations, because everything else is O(n).

You can refer to http://docs.scala-lang.org/overviews/collections/performance-characteristics.html for an overview of the runtime characteristics of different collections.

puhlen
  • 8,400
  • 1
  • 16
  • 31