Hi everyone,
While testing the fastest approach to multiply a matrix to a vector a discovered a nasty fact about reallocation.
Multiplying a matrix for a constant-defined value (namely a scalar) makes Julia reallocate the array, even within the @views
scope. If the multiplication does not happen, the memory is never reallocated.
Could you please explain to me why?
The code below shows what I mean
function network_test()
n =1000
w = rand(3,n,n) .- 0.5
r = 1:n
state = falses(n)
out = ones(Float64,n)
for tt in 1:2000
state = rand([false,true],n)
@views out = w[3,:,:]*state
end
return w
end
function network_scalar()
n =1000
w = rand(3,n,n) .- 0.5
r = 1:n
state = falses(n)
out = ones(Float64,n)
for tt in 1:2000
#
state = rand([false,true],n)
@views out = 0.1*w[3,:,:]*state
end
return w
end
using BenchmarkTools
@btime network_test()
# 2.618 s (12006 allocations: 79.20 MiB)
@btime network_scalar()
# 7.480 s (14006 allocations: 14.98 GiB)