I use vectorized operations in (NumPy/R/Matlab/...) for speed! I don't need to write loops.
The message in Julia is not that you shouldn't write vectorized code. You can write vectorized code when it is natural, but you don't have to write vectorized code just for the sake of speed. Sometimes it's more natural to write a loop. For example:
And occationally, you might want to write loops for optimization...
In [0]:
# two 200 x 200 matricies
n = 200
A = rand(n, n)
B = rand(n, n);
In [1]:
f(A, B) = 2A + 3B + 4A.*A
Out[1]:
In [2]:
using TimeIt
In [2]:
@timeit f(A, B);
In [3]:
function f2(A, B)
length(A) == length(B) || error("array length mismatch")
C = similar(A, promote_type(eltype(A),eltype(B)))
for i=1:length(C)
@inbounds a = A[i]
@inbounds C[i] = 2a + 3B[i] + 4a*a
end
return C
end
Out[3]:
In [4]:
@timeit f2(A, B)
In [7]:
function f3!(A, B, C)
length(A) == length(B) == length(C) || error("array length mismatch")
for i=1:length(C)
a = A[i]
C[i] = 2a + 3B[i] + 4a*a
end
end
Out[7]:
In [8]:
C = similar(A, promote_type(eltype(A),eltype(B)))
@timeit f3!(A, B, C)
In [ ]: