How to return a non-allocating view from a function?

Hello!

I have a function in which I do a small amount of operations, before returning a view of the final result as such:

# some operations ..
    ParticleRanges     = view(ParticleSplitterLinearIndices, ParticleSplitter)
    UniqueCells        = view(Cells,ParticleRanges[1:end-1])

    return ParticleRanges, UniqueCells 
end

I am not sure why this allocates? Is there a way to avoid such allocations, but still being able to return these variables referring to this kind of view?

I am pretty sure I can avoid allocations completely by using for example ParticleSplitterLinearIndices[ParticleSplitter] directly in the next function, but there is some very nice code coherence by returning the view explictly.

Kind regards

It’s a little hard to know without knowing more about the what is going on in your code, but my first guess would be that the call ParticleRanges[1:end-1] allocates. Can you try view(ParticleRanges,1:lastindex(ParticleRanges)-1) instead?

2 Likes

Hi!

I gave it a try but unfortunately this would increase allocations in general. ParticleSplitter is a vector of Bools, with true or false values. In combination with ParticleSplitterLinearIndices = LinearIndices(ParticleSplitter) it is used to construct the ParticleRanges variable. ParticleRanges is then used to index into the UniqueCells and construct this object.

Perhaps the code is just a bit too complex and I need to find another way, I hoped I could just get away with a view somehow…

Kind regards

Because you construct a copy of ParticleRanges

I’d try

UniqueCells        = @views Cells[ParticleRanges[1:end-1]]

Maybe that still allocates. I don’t know how well a view works in this specific case.

1 Like