# Why is inplace addition to array slice allocating?

**URL:** <https://discourse.julialang.org/t/why-is-inplace-addition-to-array-slice-allocating/103214>\
**Category:** General Usage\
**Created:** [August 26, 2023, 1:00am UTC](https://discourse.julialang.org/t/why-is-inplace-addition-to-array-slice-allocating/103214 "2023-08-26T01:00:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jeffreyesun](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreyesun/32/13379_2.png) [@jeffreyesun](https://discourse.julialang.org/u/jeffreyesun)\
**Post date:** [August 26, 2023, 1:00am UTC](https://discourse.julialang.org/t/why-is-inplace-addition-to-array-slice-allocating/103214/1 "2023-08-26T01:00:58Z")

</div>

I found an allocation in my code I wasn’t expecting. It happens when I do inplace addition `.+=` to a slice of an array. Consider the following:

```julia
foo = zeros(3,3,3)

function test1(foo)
    foo[1,:,1] .+= 2
    return nothing
end
function test2(foo)
    @views foo[1,:,1] .+= 2
    return nothing
end

@time test1(foo) # 0.000006 seconds (1 allocation: 80 bytes)
@time test2(foo) # 0.000006 seconds

```

So obviously this is pretty low-stakes, since the @views macro fixes it. But I’m curious: why does this happen? Is it safe to use @views here?

---

<div class="post-metadata">

**Author:** ![Kangaa](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kangaa/32/51765_2.png) [@Kangaa](https://discourse.julialang.org/u/Kangaa)\
**Post date:** [August 26, 2023, 3:05am UTC](https://discourse.julialang.org/t/why-is-inplace-addition-to-array-slice-allocating/103214/2 "2023-08-26T03:05:00Z")

</div>

I think it is because

```julia
foo[1,:,1] .+= 2

```

expands to

```julia
foo[1,:,1] .= foo[1,:,1] .+ 2

```

so a copy of the slice is assigned.  
see: [Allocation when assigning to a slice](https://discourse.julialang.org/t/allocation-when-assigning-to-a-slice/73381)

---

<div class="post-metadata">

**Author:** ![jeffreyesun](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreyesun/32/13379_2.png) [@jeffreyesun](https://discourse.julialang.org/u/jeffreyesun)\
**Post date:** [August 26, 2023, 3:18am UTC](https://discourse.julialang.org/t/why-is-inplace-addition-to-array-slice-allocating/103214/3 "2023-08-26T03:18:44Z")

</div>

Aha, interesting. Thanks!
