List capacity in Mojo
A List doubles its buffer as it grows, which is what makes appends cheap.
def main():
var grown = List[Int]()
for i in range(5):
grown.append(i)
print(len(grown), grown.capacity)
var sized = List[Int](capacity=64)
sized.reserve(128)
print(len(sized), sized.capacity)
How it works
- Printing
lenandcapacityon every append exposes the doubling. List[Int](capacity=64)asks for room up front.reservegrows the buffer further without adding any elements.
Keywords and builtins used here
IntListdefforlenmainprintrangevar
The run, in numbers
- Lines
- 8
- Characters to type
- 192
- Tokens
- 60
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 48 seconds.
Step 3 of 4 in Memory, step 19 of 22 in Parameters & SIMD.