# Broadcasted assignment slower than for loop when indices are arbitrary

**URL:** <https://discourse.julialang.org/t/broadcasted-assignment-slower-than-for-loop-when-indices-are-arbitrary/66729>\
**Category:** New to Julia\
**Tags:** question, broadcast\
**Created:** [August 20, 2021, 1:05pm UTC](https://discourse.julialang.org/t/broadcasted-assignment-slower-than-for-loop-when-indices-are-arbitrary/66729 "2021-08-20T13:05:13Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![mehdi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mehdi/32/28394_2.png) [@mehdi](https://discourse.julialang.org/u/mehdi)\
**Post date:** [August 22, 2021, 6:38pm UTC](https://discourse.julialang.org/t/broadcasted-assignment-slower-than-for-loop-when-indices-are-arbitrary/66729/14 "2021-08-22T18:38:16Z")

</div>

Ok this seems to be working fine (not as fast as writing a for loop but a “good” compromise):

```julia
function set_awfb!(func::F, a, w, b::Vararg{T, N}) where {F, T, N}
    for i in w
        @inbounds a[i] = func(map(x -> x[i], b)...)
    end
end

```

which is a generic version of the function suggested by @lmiq and I used splatting with `map` (suggestion found here: [Work around splatting to avoid unecessary allocations](https://discourse.julialang.org/t/work-around-splatting-to-avoid-unecessary-allocations/19708)) and type declaration (suggestion found here: [Splatting arguments causes ~30x slow down](https://discourse.julialang.org/t/splatting-arguments-causes-30x-slow-down/16964)) to avoid allocations.

An idea of the performance with a simple addition:

```julia
N = 10000;
a = ones(N); b = rand(N); c = rand(N);
w = collect(1:N)[rand(N) .< 0.5];

@btime set_awfb!(+, $a, $w, $b, $c)
  6.540 μs (0 allocations: 0 bytes)

@btime for i in $w
           @inbounds $a[i] = $b[i] + $c[i]
       end
  5.402 μs (0 allocations: 0 bytes)

@btime $a[$w] .= $b[$w] .+ $c[$w];
  17.878 μs (4 allocations: 78.03 KiB)

```

So still slower, but a good improvement compared to broadcasting!

---

_[View the full topic](https://discourse.julialang.org/t/broadcasted-assignment-slower-than-for-loop-when-indices-are-arbitrary/66729)._
