Avoid allocations in retrieving array parts

Hello,
I’m trying to reduce memory allocations and increase efficiency of our software.
Most of the allocations will occur while retrieving part of an array.

As you can see below, the retrieval is allocating much more memory than the initial array creation. Only a second view or @views will allow a smaller footprint.

@allocated array = zeros(20,2)
# 416
@allocated a = array[10,:]
# 4778152
@allocated b = view(array, 10, :)
# 2336888
@allocated @views c = array[10,:]
# 149808
@allocated @views d = array[10,:]
# 64

How can I reduce this initial allocation and how is this behavior explainable?
I looked at many other discussions about view, but I couldn’t find anything on this specific problem.

Thank you very much for any ideas!

you’re measuring allocations from compiling the method view.
This is only done once each julia session, so the more useful metric is what you get if you run it a second time:

julia> @allocated array = zeros(20,2)
       # 416
400

julia> @allocated a = array[10,:]
       # 4778152
3505352

julia> @allocated b = view(array, 10, :)
3082888

julia> @allocated b = view(array, 10, :)
64

Note that this has nothing to do with views in particular, but is generic behavior for essentially any method.

2 Likes

Ok this explains a lot, thank you!