# Weird allocation from SharedArrays/StaticArrays

**URL:** <https://discourse.julialang.org/t/weird-allocation-from-sharedarrays-staticarrays/16354>\
**Category:** Performance\
**Created:** [October 15, 2018, 5:36pm UTC](https://discourse.julialang.org/t/weird-allocation-from-sharedarrays-staticarrays/16354 "2018-10-15T17:36:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![natschil](https://avatars.discourse-cdn.com/v4/letter/n/f04885/32.png) [@natschil](https://discourse.julialang.org/u/natschil)\
**Post date:** [October 15, 2018, 5:36pm UTC](https://discourse.julialang.org/t/weird-allocation-from-sharedarrays-staticarrays/16354/1 "2018-10-15T17:36:16Z")

</div>

Hi, I’m getting an allocation from the following code, which results in a factor 20x slowdown in this MWE:

```julia

using SharedArrays,BenchmarkTools,StaticArrays

U = SharedArray{Float64}(zeros(100,100,100))
function mytestfun(U)
    function getIndices(i,j,k)
        #return U[i,j,k]
        return U[mod(i,3)+1,j,k]
    end
    uvals = @SArray [getIndices(i,j,k) for i in 1:4, j in 1:4, k in 1:4]
    return uvals[1]
end

@btime mytestfun($U)

```

Compare the code above to the same code but with line 7 uncommented, which results in it having zero allocations. Does anyone know what is going on?

---

<div class="post-metadata">

**Author:** ![platawiec](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/platawiec/32/31914_2.png) [@platawiec](https://discourse.julialang.org/u/platawiec)\
**Post date:** [October 15, 2018, 6:37pm UTC](https://discourse.julialang.org/t/weird-allocation-from-sharedarrays-staticarrays/16354/2 "2018-10-15T18:37:44Z")

</div>

I don’t have an explanation, but I have a solution:

```julia
julia> function mytestfun_faster(U)
           uvals = @SArray [U[i, j, k] for i in (mod.(1:4, 3) .+ 1), j in 1:4, k in 1:4]
           return uvals[1]
       end

julia> @btime mytestfun_faster($U)
  17.230 ns (0 allocations: 0 bytes)

```

I don’t know enough to speculate as to _why_ this is the case, but maybe it can help fill in the puzzle.

---

<div class="post-metadata">

**Author:** ![natschil](https://avatars.discourse-cdn.com/v4/letter/n/f04885/32.png) [@natschil](https://discourse.julialang.org/u/natschil)\
**Post date:** [October 15, 2018, 6:44pm UTC](https://discourse.julialang.org/t/weird-allocation-from-sharedarrays-staticarrays/16354/3 "2018-10-15T18:44:49Z")

</div>

Weird. What also seems to work is doing `U[(i-1) + (j-1)*nx*ny + (k-1)*nx*ny +1]`, i.e. converting i,j,k to a suitable linear index.
