Search code examples
rustrust-ndarray

What's the most efficient: a reference to an ArrayBase or an ArrayView?


I'm doing improvement on a Rust codebase that uses the ndarray crate to manipulate arrays. I have one question I could not find an explicit answer in the documentation.

Is it more efficient to pass an instance of ArrayView as an argument to a function or should I use a reference to an Array instead? My intuition is that since ArrayView is a view of an array, when doing computations, it only passes a view of the array and does not grant ownership to the function (hence does not copy) the underlying data.

In short, is there any speed gain to expect from switching from passing instances of ArrayView to passing references of Array?

My goal is to avoid useless memory allocation/duplication which can be very costly when dealing with large arrays.


Solution

  • ArrayBase is a generic struct that can act as both an ArrayView and an Array, so I assume you mean a reference to the owned data, i.e. an Array.

    Neither version will clone the array, so they should be approximately equally efficient. You can always benchmark to verify this.

    As I see it, the difference is mostly that ArrayView will make the function more flexible – you can pass in parts of larger arrays, or an ArrayView created from a slice, whereas the variant that takes a reference to Array can only be called when you really have an Array of the desired size.