Marching cubes without extra allocations

I would suggest first trying to rewrite the code to operate on views rather than slices, which might help you modularize the algorithm. Constructing a view() will allocate less memory than copying out a slice of an array, although it still allocates some. Fortunately, I think there’s some cool work underway to make non-allocating views possible in Julia v0.7.

Until then, if you find that your algorithm is cleaner with views, and if you want to remove the small memory allocation that each view creates, it’s possible to make an unsafe view-like object that allocates no memory at all. One example is here: https://github.com/rdeits/NNLS.jl/blob/b7314fb9691a9d4ec9897316c8732f9aba94ed47/src/NNLS.jl#L200 (based on earlier work by @tkoolen and @jrevels). This object is “unsafe” because if you keep the UnsafeVectorView around after its parent goes out of scope, then you may end up with a view of junk data. But it’s otherwise ideal for constructing lots of extremely cheap views within the inner loop of an algorithm. For example, I use these unsafe views in NNLS.jl here: https://github.com/rdeits/NNLS.jl/blob/b7314fb9691a9d4ec9897316c8732f9aba94ed47/src/NNLS.jl#L342 to efficiently grab views of my A matrix to pass to the construct_householder! function which expects an AbstractVector. This means that construct_householder! doesn’t need to know anything about the indices of A, but I also have no memory allocation penalty at all.

1 Like