# Is it worth trying to speed up setindex for arrays of numbers where an array is overwritten with another?

**URL:** <https://discourse.julialang.org/t/is-it-worth-trying-to-speed-up-setindex-for-arrays-of-numbers-where-an-array-is-overwritten-with-another/62665>\
**Category:** General Usage\
**Tags:** performance, array\
**Created:** [June 10, 2021, 10:05am UTC](https://discourse.julialang.org/t/is-it-worth-trying-to-speed-up-setindex-for-arrays-of-numbers-where-an-array-is-overwritten-with-another/62665 "2021-06-10T10:05:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jishnub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jishnub/32/33620_2.png) [@jishnub](https://discourse.julialang.org/u/jishnub)\
**Post date:** [June 10, 2021, 10:05am UTC](https://discourse.julialang.org/t/is-it-worth-trying-to-speed-up-setindex-for-arrays-of-numbers-where-an-array-is-overwritten-with-another/62665/1 "2021-06-10T10:05:39Z")

</div>

Arrays of numbers (often bitstype) are fairly common in numerical work, eg `Array{Float64}`.

I’m thinking of an operation such as

```julia
julia> a = ones(1000, 1000);

julia> b = copy(a);

julia> @btime $a[:,:] = $b;
  1.877 ms (0 allocations: 0 bytes)

julia> @btime copyto!($a, $b);
  985.943 μs (0 allocations: 0 bytes)

# It's not bounds checking either that's slowing things down, perhaps vectorization?
julia> f(a, b) = @inbounds a[:,:] = b;

julia> @btime f($a, $b);
  1.870 ms (0 allocations: 0 bytes)

# broadcasted setindex with a view is faster, but still much slower than copyto
julia> @btime $a[:,:] .= $b;
  1.572 ms (0 allocations: 0 bytes)

# direct inplace broadcasting is as fast as copyto!
julia> @btime $a .= $b;
  983.905 μs (0 allocations: 0 bytes)

```

The `setindex!` in the first case is equivalent to the broadcasted version, but the latter is doubly fast. There are instances of the opposite too, eg.

```julia
julia> @btime $a[1:size($a,1), 1:size($a,2)] = $b;
  1.873 ms (0 allocations: 0 bytes)

julia> @btime $a[1:size($a,1), 1:size($a,2)] .= $b;
  3.982 ms (0 allocations: 0 bytes)

```

The difference here is that the view is a `SlowSubArray` in this case while it was a `FastSubArray` in the former.

Does it make sense to identify such cases where a potentially slow operation may be replaced by a faster one, and use the faster implementation instead? I’m not sure how generic this will be, however this might improve the performance in common applications. Otherwise it requires the user to retain a list of which operation is faster in each scenario to obtain optimal performance.

Ideally all these operations would behave identically, but I’m not sure if it’s easy to get there.

I had posted [an issue](https://github.com/JuliaLang/julia/issues/40962) about this a which seemingly didn’t get much attention, so I thought about discussing this here.
