Slow behavior of containers.Map
3 views (last 30 days)
Show older comments
In using containers.Map to count the occurrence of certain events I noticed rather slow behavior of the object, specifically when compared to other methods I thought would be less elegant.
Below is the test code. We loop through numbers 1 through 5 and want to count how often each appears. I use four different methods, two using containers.Map, one using find(), and one using switch ... case.
%% containers.Map test script
% create test key list, value list and Map
keyList = [1 2 3 4 5];
valueList = zeros(size(keyList));
c1 = containers.Map(keyList, valueList);
c2 = containers.Map(keyList, valueList);
% prepare result vectors
findCounter = zeros(size(keyList));
switchCounter = zeros(size(keyList));
% now count something
testVector = repelem(1:5, 1, 1e5);
% now count occurrence of each number
for ii = testVector
% use c.isKey(ii)
if c1.isKey(ii)
c1(ii) = c1(ii) + 1;
end
% use isKey(c, ii)
if isKey(c2, ii)
c2(ii) = c2(ii) + 1;
end
% use find()
a = find(keyList == ii, 1);
if ~isempty(a)
findCounter(a) = findCounter(a) + 1;
end
% use switch ... case
switch ii
case 1
switchCounter(1) = switchCounter(1) + 1;
case 2
switchCounter(2) = switchCounter(2) + 1;
case 3
switchCounter(3) = switchCounter(3) + 1;
case 4
switchCounter(4) = switchCounter(4) + 1;
case 5
switchCounter(5) = switchCounter(5) + 1;
end
end
When running the profiler (see picture below), we can notice several aspects:
1.)
c1.isKey(ii)
is significantly slower than
isKey(c2, ii)
Why is that?
2.) The "brute force" approach using find() is significantly faster than either of the containers.Map techniques. Why is that? Just like the isKey function we are searching a vector of 5 elements at every instance.
3.) The switch ... case approach is much faster any other method. But isn't the switch, case logic manually evaluating 5 elements just like the find() and isKey() functions?
It seems to me the less elegant the implementation here, the faster the computation. Or am I making a mistake somewhere?
Thanks for any guidance!

0 Comments
Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!