Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala append and prepend method performance

Tags:

scala

I was following a Scala video tutorial and he mentioned prepend :: takes constant time and append :+ time increases with length of list. And, also he mentioned most of the time reversing the list prepending and re-reversing the list gives better performance than appending.

Question 1
Why prepend :: takes constant time and append :+ time increases with length of list?

But reason for that is not mentioned in the tutorial and I tried in google. I didn’t find the answer but I found another surprising thing.

Question 2
ListBuffer takes constant time for both append and prepend. If possible why it wasnt implemented in List?

Obvious there would be reason behind! Appreciate if someone could explain.

like image 774
WoodChopper Avatar asked Oct 27 '25 23:10

WoodChopper


1 Answers

Answer 1: List is implemented as Linked list. The reference you hold is to it's head. e.g. if you have a list of 4 elements (1 to 4) it will be:

[1]->[2]->[3]->[4]->//

Prepending meaning adding new element to the head and return the new head:

[5]->[1]->[2]->[3]->[4]->//

The reference to the old head [1] still valid and from it's point of view there are still 4 elements.
On the other hand, appending meaning adding element to the end of the list. Since List is immutable, we can't just add it to the end, but we need to clone the entire List:

[1']->[2']->[3']->[4']->[5]->//

Since clone mean copy the entire list in the same order, we need to iterate over each element and append it.

Answer 2: ListBuffer is mutable collection, changing it will change all the references.

like image 54
roterl Avatar answered Oct 30 '25 19:10

roterl