4 ms·
I've found Rust to be great at avoiding allocations. You can return a pre-allocated buffer to be shared by all callers from a function in a safe way that preve
by sixbrx 13y ago
I've found Rust to be great at avoiding allocations.
You can return a pre-allocated buffer to be shared by all callers from a function in a safe way that prevents interference between callers. The callers only get to keep it for a limited time (region, actually), but usually that's no issue.
In exchange, the callers are gauranteed that the returned buffer contents can't be modified by any other part of the program while it is borrowed.
Here's some code for multiplying some polynomial vectors which uses this style, without allocating (except for a single initial allocation of the buffer):
https://github.com/scharris/WGFEM-Rust/blob/master/weak_gradient.rs#L275 https://github.com/scharris/WGFEM-Rust/blob/master/weak_grad...
Line 275: The structure holding the buffer and on which the operations are implemented.
Line 287: the buffer field
Line 297: The operation returning a structure (by value) which has an immutable "borrow" of the shared buffer. It's lifetime is tagged with lifetime 'a, tied to the lifetime of the implementing object.
Line 319: The buffer being included in the return value.
I really like the pattern. Get the efficiency of not allocating, kindof like old school libraries like LAPACK, without doing things like writing over your inputs :)