# Avoid allocations in retrieving array parts

**URL:** <https://discourse.julialang.org/t/avoid-allocations-in-retrieving-array-parts/121908>\
**Category:** Performance\
**Tags:** question, array, views\
**Created:** [October 29, 2024, 9:17am UTC](https://discourse.julialang.org/t/avoid-allocations-in-retrieving-array-parts/121908 "2024-10-29T09:17:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![JTHesse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jthesse/32/212000_2.png) [@JTHesse](https://discourse.julialang.org/u/JTHesse)\
**Post date:** [October 29, 2024, 9:17am UTC](https://discourse.julialang.org/t/avoid-allocations-in-retrieving-array-parts/121908/1 "2024-10-29T09:17:00Z")

</div>

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.

```julia
@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!

---

<div class="post-metadata">

**Author:** ![Salmon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/salmon/32/22968_2.png) [@Salmon](https://discourse.julialang.org/u/Salmon)\
**Post date:** [October 29, 2024, 9:27am UTC](https://discourse.julialang.org/t/avoid-allocations-in-retrieving-array-parts/121908/2 "2024-10-29T09:27:23Z")

</div>

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
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.

---

<div class="post-metadata">

**Author:** ![JTHesse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jthesse/32/212000_2.png) [@JTHesse](https://discourse.julialang.org/u/JTHesse)\
**Post date:** [October 29, 2024, 9:32am UTC](https://discourse.julialang.org/t/avoid-allocations-in-retrieving-array-parts/121908/3 "2024-10-29T09:32:11Z")

</div>

Ok this explains a lot, thank you!
