我将带有 char 键的 container.Map(感谢 Andrew Janke)与带有包装器对象作为键的 java.util.HashMap 进行了比较(在这篇文章中,也感谢 Andrew Janke,并感谢 Rasman 指出):
numvec = 10^5;
S = round(rand(numvec,10)*40);
matmap = containers.Map();
%pick a random vector
idx = ceil(rand()*numvec);
s1 = S(idx,:);
%put it in the map
matmap(char(s1)) = zeros(1,4);
for i=1:5*10^5
if i==10^3 tic; end %allow some time for getting up to speed before timing
%pick a random vector and put it in the map
idx = ceil(rand()*numvec);
s2 = S(idx,:);
matmap(char(s2)) = zeros(1,4);
%retrieve value of previous vector
v = matmap(char(s1));
%modify it randomly and put it back
v( ceil(rand()*4) ) = rand();
matmap(char(s1)) = v;
s1 = s2;
end
toc
javaaddpath('/Test/bin');
import test.ArrayKey;
javmap = java.util.HashMap;
idx = ceil(rand()*numvec);
s1 = S(idx,:);
%also convert value to ArrayKey so we can retrieve it by ref -- saves a put
%operation
javmap.put(ArrayKey(s1), ArrayKey(zeros(1,4)));
for i=1:5*10^5
if i==10^3 tic; end
idx = ceil(rand()*numvec);
s2 = S(idx,:);
javmap.put(ArrayKey(s2), ArrayKey(zeros(1,4)));
v = javmap.get(ArrayKey(s1));
v.x( ceil(rand()*4) ) = rand();
s1 = s2;
end
toc
结果:
>> testmaps
Elapsed time is 58.600282 seconds.
Elapsed time is 97.617556 seconds.
container.Map 是赢家。
编辑:我重新运行了 numvec = 10^6 的测试,其他一切都一样。container.Map 方法在 59 秒内运行。HashMap 方法在 5 分钟后未完成,导致 Matlab 无响应。
Edit2:我还尝试预先分配两个单独的矩阵并使用ismember
. 性能比 HashMap 差。