tryingtosolve
tryingtosolve

Reputation: 803

Julia - why are loops faster

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:

  1. Why are loops faster?
  2. If loops are indeed faster, are there "smart" vectorization techniques that mimic loops? The syntax for loops is ugly and long.

Upvotes: 4

Views: 1275

Answers (2)

DNF
DNF

Reputation: 12664

  1. 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.

  2. 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

sam
sam

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

Related Questions