Hacker News new | ask | show | jobs
by vlovich123 246 days ago
You misread the documentation. Reserve-exact is precisely that - the growth strategy is ignored and you are ensured that at least that many more elements can be inserted without a reallocation. Eg reserve_exact(100) on an empty Vec allocates space for 100 elements.

By contrast reserve will allocate space for the extra elements following the growth strategy. If you reserve(100) on an empty Vec the allocation will be able to actually insert 128 (assuming the growth strategy is pow(n))

1 comments

Actually that's not quite correct.

Vec::reserve(100) on an empty Vec will give you capacity 100, not 128 even though our amortization is indeed doubling.

The rules go roughly like this, suppose length is L, present capacity is C, reserve(N):

1. L + N < C ? Enough capacity already, we're done, return

2. L + N <= C * 2 ? Ordinary doubling, grow to capacity C * 2

3. Otherwise, try to grow to L + N

This means we can grow any amount more quickly than the amortized growth strategy or at the same speed - but never less quickly. We can go 100, 250, 600, 1300 and we can go 100, 200, 400, 800, 1600 - but we can''t do 100, 150, 200, 250, 300, 350, 400, 450, 500...