# Local arrays in for loops

**URL:** <https://discourse.julialang.org/t/local-arrays-in-for-loops/56216>\
**Category:** New to Julia\
**Created:** [February 28, 2021, 10:47pm UTC](https://discourse.julialang.org/t/local-arrays-in-for-loops/56216 "2021-02-28T22:47:48Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![Ribeiro](https://avatars.discourse-cdn.com/v4/letter/r/d9b06d/32.png) [@Ribeiro](https://discourse.julialang.org/u/Ribeiro)\
**Post date:** [March 1, 2021, 8:59am UTC](https://discourse.julialang.org/t/local-arrays-in-for-loops/56216/8 "2021-03-01T08:59:37Z")

</div>

@Mason I started with a regular matrix and when I switched to a Vector of StaticArrays my code became 10x faster.  
@lmiq Thanks for the link. I learned some stuff =].

I thought this was a common enough problem that I wouldn’t need to make a full example, but here’s one:

```julia
N=1000;
vertexList = Vector{StaticArrays.SVector{3,Float64}}(undef,N);
elements = Vector{StaticArrays.SVector{3,Int}}(undef,N);
for i in 1:1000
    vertexList[i] = SA_F64[rand(),rand(),rand()];
    elements[i] = SA[rand(1:N),rand(1:N),rand(1:N)];
end
elementLength = length(elements[1]);
v = collect(1:elementLength);
vNext = v.%elementLength .+ 1;

function temp1(vertexList,elements,N)
    for k in 1:N
        vertices = vertexList[elements[k]];
        edges = vertices[vNext]-vertices[v];
        edgesNorm = norm.(edges);
    end
end
function temp2(vertexList,elements,N)
    for k in 1:N
        vertex1= vertexList[elements[k][1]]; vertex2= vertexList[elements[k][2]]; vertex3= vertexList[elements[k][3]];
        edge1 = vertex2-vertex1; edge2 = vertex3-vertex2; edge3 = vertex1-vertex3;
        edgeNorm1 = norm(edge1); edgeNorm2 = norm(edge2); edgeNorm3 = norm(edge3);
    end
end
@btime temp1(vertexList,elements,N); # 1.054 ms (8000 allocations: 765.63 KiB)
@btime temp2(vertexList,elements,N); # 991.583 ns (0 allocations: 0 bytes)

```

So `temp2` is waaaay better, but way less elegant. It also locks me in a certain `elementLength`.  
Any tips?  
Thanks a lot!

---

_[View the full topic](https://discourse.julialang.org/t/local-arrays-in-for-loops/56216)._
