我有MATLAB的背景,所以我倾向于矢量化一切.但是,在Julia,我测试了这两个函数: function testVec(n) t = [0 0 0 0]; for i = 1:n for j = 1:4 t[j] = i; end endendfunction testVec2(n) t = [0 0 0 0]; for i = 1:n t.= [i i i
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)
我有两个问题:
>为什么循环更快?
>如果循环确实更快,是否存在模仿循环的“智能”矢量化技术?循环的语法是丑陋和冗长的.
function testVec3(n)
t = [0 0 0 0]
for i=1:n
t .= i
end
end
