I have a relatively large matrix, where I want to set all values below a certain threshold to zero:
@time A = rand(1000,1000,1000)
@time bool = A .< 0.5
@time A[bool] .= 0.0
5.653554 seconds (2 allocations: 7.451 GiB, 2.64% gc time)
1.698547 seconds (6 allocations: 119.214 MiB, 20.14% gc time)
5.429685 seconds (5 allocations: 3.725 GiB, 1.63% gc time)
I would have expected the final step to allocate essentially no memory since I am overwriting elements of an existing array in-place, however the amount of actually allocated memory equals that of creating an entirely new array containing the overwritten values (Julia 1.7.2).
Interestingly, when I instead use a view, the allocations occur during the creation of the view rather than the overwriting step.
@time Av = @view A[bool]
@time Av .= 0.0
2.786945 seconds (5 allocations: 3.725 GiB, 9.23% gc time)
1.292666 seconds
Could anyone help me understand why these allocations occur and whether there is a way to avoid them?