Reputation: 803
I have a background in MATLAB so I have the tendency to vectorize everything. However, in Julia, I tested these two functions:
function testVec(n)
t = [0 0 0 0];
for i = 1:n
for j = 1:4
t[j] = i;
end
end
end
function testVec2(n)
t = [0 0 0 0];
for i = 1:n
t.= [i i i i];
end
end
@time testVec(10^4)
0.000029 seconds (6 allocations: 288 bytes)
@time testVec2(10^4)
0.000844 seconds (47.96 k allocations: 1.648 MiB)
I have two questions:
Upvotes: 4
Views: 1275
Reputation: 12664
It's all loops under the hood. The vectorized expressions get translated to loops, both in Julia and in Matlab. In the end it's all loops. In your particular example, it is as @sam says, because you're allocating a bunch of extra arrays that you can avoid if you loop explicitly. The reason you still do so in Matlab is that then everything gets shuffled into functions that are written in a high-performance language (C or Fortran, probably), so it's worth it even when you do extra allocations.
Indeed there are, as @sam showed. Here's a blog post that tells you all you need to know about broadcasting and loop fusion.
Upvotes: 5
Reputation: 56
In the testVec2
method, the code will allocate a temporary vector for holding [i i i i]
for every instance of i
in your loop. This allocation is not for free. You can see evidence of this in the number of allocations printed in your timing results. You could try the following:
function testVec3(n)
t = [0 0 0 0]
for i=1:n
t .= i
end
end
Upvotes: 4