简体   繁体   中英

Scala append and prepend method performance

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.

Answer 1: List is implemented as Linked list. The reference you hold is to it's head. eg 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.

Ad. 1. The list in Scala is defined (simplifying) as a head and a tail. The tail is also a list. Adding an element to the head means creation a new list with a new head and the existing list as a new tail. The existing list is not changed. This is why it is a constant time operation. Appending to a list needs rebuilding the existing list, which cannot be done in constant time.

Ad. 2. ListBuffer is a mutable collection. It may be more efficient in some applications, but on the other hand immutable collections are thread-safe and easily scalable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM