# Avoid allocations on broadcasted getindex()

**URL:** <https://discourse.julialang.org/t/avoid-allocations-on-broadcasted-getindex/105098>\
**Category:** Performance\
**Created:** [October 18, 2023, 1:16am UTC](https://discourse.julialang.org/t/avoid-allocations-on-broadcasted-getindex/105098 "2023-10-18T01:16:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ejmeitz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ejmeitz/32/45283_2.png) [@ejmeitz](https://discourse.julialang.org/u/ejmeitz)\
**Post date:** [October 18, 2023, 1:16am UTC](https://discourse.julialang.org/t/avoid-allocations-on-broadcasted-getindex/105098/1 "2023-10-18T01:16:51Z")

</div>

If I have the code below is there someway to do this without allocating intermediate arrays? It feels like it should be possible but I cant figure it out. I can do this without allocating if I was indexing with a range, but my problem is such that I index with a random-ish array of integers that is much longer than the size of the vector. Any help would be greatly appreciated!

```julia
phi = rand(500,500)
N = 10000000; m = 32, n = 51
is = rand(1:500, N); js = rand(1:500, N); vals = rand(N);
phi_n = view(phi:,n); phi_m = view(phi,:,m)
## Specifically this calculation -- allocates on the getindex.()
mcc_val = sum(vals .* getindex.(Ref(phi_n), is) .*
                 getindex.(Ref(phi_m), js))

```

---

<div class="post-metadata">

**Author:** ![ejmeitz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ejmeitz/32/45283_2.png) [@ejmeitz](https://discourse.julialang.org/u/ejmeitz)\
**Post date:** [October 18, 2023, 1:25am UTC](https://discourse.julialang.org/t/avoid-allocations-on-broadcasted-getindex/105098/2 "2023-10-18T01:25:39Z")

</div>

Realized for-loop works at the cost of my code looking uglier and having to re-arrange some structs.

---

<div class="post-metadata">

**Author:** ![ffevotte](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ffevotte/32/6587_2.png) [@ffevotte](https://discourse.julialang.org/u/ffevotte)\
**Post date:** [October 18, 2023, 9:53am UTC](https://discourse.julialang.org/t/avoid-allocations-on-broadcasted-getindex/105098/3 "2023-10-18T09:53:36Z")

</div>

Something like this should work:

```julia
mcc_val = sum(vals[k] * phi[n, is[k]] * phi[m, js[k]] for k in 1:N)

```

Would that look “less ugly” to you than a for loop?
