Stream: beginners

Topic: Semantics of List.reserve and performance characteristics


view this post on Zulip Matthieu Pizenberg (Aug 18 2026 at 15:04):

Currently, the documentation of List.reserves reads: "Ensure this list has room for at least spare additional items.". I thought for example that if I do reserve(2) it would just make sure that there is at least 2 empty spaces to add new elements. But my current experiment, in a linux VM, results in quadratic performance behavior when using reserve.

In practice, a minimal example showing the problematic perf behavior would look like this:

var $xs = []
while $xs.len() < n {
    $xs = $xs.reserve(2)
    $xs = $xs.append(0)
    $xs = $xs.append(0)
}

Doing this results in quadratic timing increase when n increases. If we remove the reserve line instead, the time grows roughly linearly with n.

What are your thoughts about that? Should I open an issue? Is that specific to the platform I’m using (the default one) or a problem across platforms?

view this post on Zulip Anton (Aug 18 2026 at 15:37):

I will dig into this

view this post on Zulip Anton (Aug 18 2026 at 16:12):

Yeah the docs are very light on detail :smile: I will fix that.

view this post on Zulip Anton (Aug 18 2026 at 16:13):

List.reserve should say it allocates exactly len + spare and reallocates+copies whenever spare exceeds current slack. So, the docs should mention it belongs outside loops, and repeated small reserves are O(n²).

view this post on Zulip Anton (Aug 18 2026 at 16:17):

If we remove the reserve line instead, the time grows roughly linearly with n.

Roc reserves many more elements by default so it needs to a lot less copying in this case.

view this post on Zulip Anton (Aug 18 2026 at 17:08):

Anton said:

Yeah the docs are very light on detail :smile: I will fix that.

PR#10852


Last updated: Sep 03 2026 at 15:16 UTC