Why is appending to a list bad?

前端 未结 5 1253
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 01:18

I\'ve recently started learning scala, and I\'ve come across the :: (cons) function, which prepends to a list.
In the book \"Programming in Scala\" it state

5条回答
  •  日久生厌
    2020-12-01 01:58

    Prepending is faster because it only requires two operations:

    1. Create the new list node
    2. Have that new node point to the existing list

    Appending requires more operations because you have to traverse to the end of the list since you only have a pointer to the head.

    I've never programmed in Scala before, but you could try a List Buffer

提交回复
热议问题