# Avoiding allocations in small subvector ops

**URL:** <https://discourse.julialang.org/t/avoiding-allocations-in-small-subvector-ops/88500>\
**Category:** Performance\
**Created:** [October 9, 2022, 10:39pm UTC](https://discourse.julialang.org/t/avoiding-allocations-in-small-subvector-ops/88500 "2022-10-09T22:39:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Stephen\_Vavasis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stephen_vavasis/32/3389_2.png) [@Stephen\_Vavasis](https://discourse.julialang.org/u/Stephen_Vavasis)\
**Post date:** [October 9, 2022, 10:39pm UTC](https://discourse.julialang.org/t/avoiding-allocations-in-small-subvector-ops/88500/1 "2022-10-09T22:39:28Z")

</div>

In the code below, there is an allocation each time the statement `u[i1:i1+1].=...` is executed. A few years ago, I wrote a quick-and-dirty macro to implement statements like this with a for-loop like the commented-out loop in the code below. I suppose now there is a standard macro that implements the statement with a for-loop. Or maybe there is a better way to use dot-notation to avoid the allocation.

```julia
function many_vector_adds(n,ncopy)
    u = zeros(n)
    for i = 1 : n
        u[i] = i
    end
    for i = 1 : ncopy
        i1 = Int(floor(sin(i)^2 * (n - 1))) + 1
        i2 = Int(floor(cos(i)^2 * (n - 1))) + 1
        u[i1 : i1 + 1] .= u[i1 : i1 + 1] ./ 2 .+ u[i2 : i2 + 1]        
        #for j = 0 : 1
        # u[i1 + j] = u[i1 + j] / 2 + u[i2 + j]
        #end

    end
    u[100]
end
@time many_vector_adds(10_000, 1_000_000)

```

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [October 9, 2022, 11:41pm UTC](https://discourse.julialang.org/t/avoiding-allocations-in-small-subvector-ops/88500/2 "2022-10-09T23:41:43Z")

</div>

> [@Stephen\_Vavasis](#):
>
> `@views u[i1 : i1 + 1] .= u[i1 : i1 + 1]...`

I think what allocates there are the slices on the right side.

---

<div class="post-metadata">

**Author:** ![Stephen\_Vavasis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stephen_vavasis/32/3389_2.png) [@Stephen\_Vavasis](https://discourse.julialang.org/u/Stephen_Vavasis)\
**Post date:** [October 10, 2022, 1:03am UTC](https://discourse.julialang.org/t/avoiding-allocations-in-small-subvector-ops/88500/3 "2022-10-10T01:03:07Z")

</div>

Thanks, that worked!
