我有MATLAB的背景,所以我倾向于将所有东西向量化。然而,在Julia中,我测试了这两个函数:
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)
我有两个问题:
- 为什么循环更快?
- 如果循环确实更快,那么是否有“智能”向量化技术可以模仿循环?循环的语法又丑又长。
bsxfun
向量化技巧实际上很难阅读的人吗?在某些情况下,我们只需要循环,这样应该会更快 ;) - Gnimuc