I am evaluating performance of arrays construction in Julia using comprehensions or explicit loops by comparing the following sample codes.
Code 1:
function foo()
s = 500
n = 9000
m = zeros(s, s)
tic()
for k = 1:n
for i in 1:s, j in 1:s m[i, j] = j end
end
toc()
end
Code 2:
function foo()
s = 500
n = 9000
m = zeros(s, s)
tic()
for k = 1:n
m = [j for i in 1:s, j in 1:s]
end
toc()
end
Code 3:
function foo()
s = 500
n = 9000
m = zeros(s, s)
tic()
for k = 1:n
m .= [j for i in 1:s, j in 1:s]
end
toc()
end
On my PC, code 1 runs in about 5.4 s, code 2 in about 8.3 s, and code 3 in about 12.9 s.
I guess that code 2 is slightly slower than code 1 due to the temporary array allocation cost, but I would have expected code 3 to be roughly in par with code 1 thanks to vectorization.
Similarly I verified that the following code:
m = rand(s, s)
is faster than the following code, when tested as before:
m .= rand(s, s)
What is Julia doing in these cases when using .=
?
Thanks