# Why are for loops slower than broadcast with splatted arguments?

**URL:** <https://discourse.julialang.org/t/why-are-for-loops-slower-than-broadcast-with-splatted-arguments/30801>\
**Category:** New to Julia\
**Tags:** performance, tuple\
**Created:** [November 6, 2019, 6:02pm UTC](https://discourse.julialang.org/t/why-are-for-loops-slower-than-broadcast-with-splatted-arguments/30801 "2019-11-06T18:02:42Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![jlchan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlchan/32/10958_2.png) [@jlchan](https://discourse.julialang.org/u/jlchan)\
**Post date:** [November 6, 2019, 7:55pm UTC](https://discourse.julialang.org/t/why-are-for-loops-slower-than-broadcast-with-splatted-arguments/30801/5 "2019-11-06T19:55:43Z")

</div>

I think I figured out why it’s so slow - I wasn’t being careful with tuples and arrays.

In the original splatted loop code, I’m splatting the X\_entry, Y\_entry arguments, which (I guess) converts from an Array to a Tuple.

```julia
function foo_loop_splat!(N,X,Y,Xi,Yi)
    for i = 1:N
        for fld in eachindex(X)
            Xi[fld] = X[fld][i]
            Yi[fld] = Y[fld][i]
        end
        foo(Xi...,Yi...)
    end
end

```

An old post by @rdeits on [Array of tuples - #7 by rdeits](https://discourse.julialang.org/t/array-of-tuples/11435/7) noted that tuples have much less overhead compared to arrays. If I replace the for loop with the (simpler) tuple-based version

```julia
function foo_loop_splat!(N,X,Y)
    for i = 1:N
        foo(getindex.(X,i)...,getindex.(Y,i)...)
    end
end

```

then the non-splatted and splatted for loop give identical runtimes

```julia
@btime foo_loop($N,$a,$b,$c,$d)
@btime foo_loop_splat!($N,$X,$Y)

```

```julia
  1.049 ms (0 allocations: 0 bytes)
  1.093 ms (0 allocations: 0 bytes)

```

---

_[View the full topic](https://discourse.julialang.org/t/why-are-for-loops-slower-than-broadcast-with-splatted-arguments/30801)._
