List memory preallocation

Is this the correct way to preallocate memory in Mojo?
var large_list = List[int](capacity=5)
var large_list = List[int](capacity=5)
Also with what is the memory preallocate (Null, 0,)? What is the difference between size and capacity? Does memory preallocation give me a performance improvment in Mojo?
2 Replies
Nick!
Nick!2w ago
The "size" of the list is about to be renamed to "len", which hopefully clarifies what it means. The "capacity" of a container is the number of elements that memory has been allocated for. It is always >= the length. If you know any Rust, see this explanation. So yes, List[Int](capacity=5) gives you a list of length zero, with memory reserved for 5 elements.
Does memory preallocation give me a performance improvement in Mojo?
It's very difficult to reason about program performance without benchmarking. Modern compilers are smart and can provide great performance without manual intervention. Whether or not manually specifying the capacity of your list can improve performance depends upon what capacity value you're specifying, and how many elements you put in your list. In general, there will likely be a small (but measurable) performance difference when reserving a large number of elements, but not when reserving a small number of elements (≤ 4).
whatever
whateverOP2w ago
Thanks

Did you find this page helpful?