Stream: beginners

Topic: List performance?


view this post on Zulip Johan Lövgren (Dec 13 2023 at 11:29):

A few months ago I had the understanding that in general it was better to "do things" at the end of a List instead of at the start. So appending a value is much more performant than prepending a value for example. But now I have seen some discussions about "seamless slices" changing this. But I can't quite wrap my head around what that means. Is it still better to append than to prepend for example? I would like to learn more here :smile:

view this post on Zulip Brian Carroll (Dec 13 2023 at 11:56):

The "seamless slice" feature allows us to share data between lists. For example the sublist function returns a seamless slice. If you ask for elements 5-10 of a list, it will not create a whole new memory allocation for it and copy the contents across. Instead, it just returns a structure that refers to part of the original list. It contains metadata that says "Hey I'm really a slice, not a real List. I refer to the elements of this other list at address 0xabc123456, starting at offset 5 with length 6"
If you then modify that list in any way, making it different from the original list, we have to create a new one and copy the contents. There's no way around it.

view this post on Zulip Brian Carroll (Dec 13 2023 at 11:56):

But if you don't modify it, it's way more efficient to just share the data instead of allocating and copying.

view this post on Zulip Brian Carroll (Dec 13 2023 at 11:58):

So the situation has gotten more complex for sure.
BUT if you are trying to decide "should I append or prepend", then definitely append rather than prepend! Prepending is never better. It is either the same (if you were doing a copy anyway) or worse, but never better.

view this post on Zulip Johan Lövgren (Dec 13 2023 at 16:05):

Thanks for the great explanation! That makes a lot of sense.


Last updated: Jul 06 2025 at 12:14 UTC