たとえば、次のクラスがあります。
classdef testclass < handle
properties
buckets
end
methods
function tc = testclass(sz)
tc.buckets = cell(1, sz);
end
function put(tc,k)
tc.buckets{k}{1} = 1;
end
end
end
そして、次のループの例では、パフォーマンスをプレーンセル配列と比較しています。
tm = @java.lang.System.currentTimeMillis;
for N=[100 200 400 1000 2000 4000 8000]
tc = testclass(N);
Tstart = tm();
for k=1:N
tc.put(k);
end
Tend = tm();
fprintf(1, 'filling hash class (size %d): %d ms\n', N, Tend - Tstart);
arr = cell(1,N);
Tstart = tm();
for k=1:N
arr{k}{1} = 1;
end
Tend = tm();
fprintf(1, 'filling cell array (size %d): %d ms\n', N, Tend - Tstart);
end
出力は次のとおりです。
filling hash class (size 100): 8 ms
filling cell array (size 100): 0 ms
filling hash class (size 200): 9 ms
filling cell array (size 200): 0 ms
filling hash class (size 400): 24 ms
filling cell array (size 400): 1 ms
filling hash class (size 1000): 108 ms
filling cell array (size 1000): 2 ms
filling hash class (size 2000): 370 ms
filling cell array (size 2000): 5 ms
filling hash class (size 4000): 1396 ms
filling cell array (size 4000): 10 ms
filling hash class (size 8000): 5961 ms
filling cell array (size 8000): 21 ms
ご覧のとおり、プレーンセル配列は「線形」パフォーマンスを示しますが(これは予想されることです)、クラスにラップされた配列は恐ろしい2次パフォーマンスを提供します。
これをMatlab2008aとMatlab2010aでテストしました。
これの原因は何ですか?そして、どうすればそれを回避できますか?