I am trying to understand inplace assignment in julia.
In the following example I want to update a and b. The following code works, and it updates a and b in place without any allocations.
n = 1000
a = ones(n,1)
b = ones(n,1)
c = 1.0
d = 2.0
nsel = rand(n) .> 0.5
function testalloc!(a, b, c, d, nsel)
@. a = c * a + d * b
@. b = d * a + c * b
end
@btime testalloc!(a, b, c, d, nsel)
891.646 ns (0 allocations: 0 bytes)
However, if i have to do it for a subset there are 28 allocations and it is slower
function testalloc1!(a, b, c, d, nsel)
@. a[nsel] = c * a[nsel] + d * b[nsel]
@. b[nsel] = d * a[nsel] + c * b[nsel]
end
@btime testalloc1!(a, b, c, d, nsel)
3.350 Ī¼s (28 allocations: 24.22 KiB)
and if I wanted to do for the complementary subset there are 40 allocationsā¦ and it is even more slower
function testalloc2!(a, b, c, d, nsel)
@. a[.!nsel] = c * a[.!nsel] + d * b[.!nsel]
@. b[.!nsel] = d * a[.!nsel] + c * b[.!nsel]
end
@btime testalloc2!(a, b, c, d, nsel)
3.775 Ī¼s (40 allocations: 27.13 KiB)
Could someone please help me understand the correct way to update subsets of arrays.
Thank You