I did some tests, and looks like a seq is resized before actually needing it:
proc main(useAdd: static[bool]) =
const TOTAL = 10_000_000
var s: seq[int] = when useAdd: newSeqOfCap[int](TOTAL)
else: newSeq[int](TOTAL)
for i in 0 .. <TOTAL:
when useAdd: add s, i
else: s[i] = i
echo "----"
echo "LEN: ", len(s)
echo("SIZ: ", (len(s) * 4) / 1024)
echo "RAM: ", getOccupiedMem() / 1024
echo "----"
main(false)
GC_fullCollect()
main(true)
this prints:
----
LEN: 10000000
SIZ: 39062.5
RAM: 39120.0
----
----
LEN: 10000000
SIZ: 39062.5
RAM: 88948.0
----
I would expect the resize to occurs when seq actually needs it, and not before. Maybe i want to make sure a seq doesn't take more space than needed. But if i'm right, i might need to give it +1 size to avoid the resize. Am i wrong here?
this might help to detect a hidden resize.
proc cap*[T](s: seq[T]): Natural =
cast[ptr tuple[length, capacity: Natural]](s).capacity
I really wonder why this is not part of the system module.