这可能是由内存分配引起的.情况1的陈述
for x=V
必须创建V的副本.我们为什么知道?如果您在循环内修改V,则x不会受到影响:它仍将通过原始V值运行.
另一方面,情况2的陈述
for ind=1:numel(V)
实际上并没有创建向量1:numel(V).从帮助,
Long loops are more memory efficient when the colon expression appears in the for statement since the index vector is never created.
不需要分配内存的事实可能至少在一定程度上说明了速度的提高.
为了测试这一点,让我们将ind = 1:numel(V)更改为ind = [1:numel(V)].这将强制创建矢量1:numel(V).然后,运行时间应该与情况1相似,或者实际上会更长一些,因为我们仍然需要使用V(ind)索引到V.
这些是我计算机上的运行时间:
% Case 1
n=50000000;
V =1:n;
s1 = 0;
tic
for x=V
s1 = s1+x;
end
toc
% Case 2
s2 = 0;
tic
for ind=1:numel(V)
s2 = s2+V(ind);
end
toc
% Case 3
s3 = 0;
tic
for ind=[1:numel(V)]
s3 = s3+V(ind);
end
toc
结果:
Elapsed time is 0.610825 seconds.
Elapsed time is 0.182983 seconds.
Elapsed time is 0.831321 seconds.