typestar

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

  1. Printing len and capacity on every append exposes the doubling.
  2. List[Int](capacity=64) asks for room up front.
  3. reserve grows the buffer further without adding any elements.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Memory, step 19 of 22 in Parameters & SIMD.

← Previous Next →