In place updating of arrays

Julia is doing everything correctly. Operation a + b requires 1 allocation to create a new array and c = ... binds variable c to this new array. Binding does not require allocation.

In other words, c = a + b is roughly equivalent to

temp = Vector{Float64}(undef, 100)
for i in 1:100
   temp[i] = a[i] + b[i]
end
c = temp

If you want inplace operation, you need to use . both in + and =. Then this operations are fused together and turns into inplace update. I.e. c .= a .+ b is equivalent to

for i in 1:100
  c[i] = a[i] + b[i]
end

UPD: operation c .= a + b is rather meaningless, because it is equivalent to

temp = Vector{Float64}(undef, 100)
for i in 1:100
   temp[i] = a[i] + b[i]
end

for i in 1:100
  c[i] = temp[i]
end

so it run even slower than c = a + b because instead of binding variable, it copies data.

7 Likes