Hello all,
I was trying to decide between using a containers.Map, fields of a struct, or properties of a class for a simple application when I found something curious.
Both isfield(s) and isKey(m) for s a struct and m a map are relatively quick and appear independent of the number of fields and keys, respectively, as one would expect from any decent hash table.
However, isprop(c) for c a class was radically slower – and appears to become even slower when more properties are added.
Here is the code I used – am I doing something wrong? Or is accessing properties simply just that slow?
nfields = 100; % Try 10000 and 1 as well.
%%This section writes the testclass. After changing the number of fields,
% you may need to clear classes or restart MATLAB. For a given number of
% fields, this section only needs to be run once.
fp = fopen('testclass.m','w');fprintf(fp,'classdef testclass\n');fprintf(fp,'properties\n');for i=1:nfields fprintf(fp,'p%d = %d;\n',i,i);endfprintf(fp,'end\n');fprintf(fp,'end\n');fclose(fp);%%This section generates map, struct, and class of interest.
clear s;m = containers.Map;for i=1:nfields s.(sprintf('p%d',i)) = i; m(sprintf('p%d',i)) = i;endc = testclass;%%This loop tests the speed of the isfield operation for MATLAB structs
% Run it a few times to get a feel for the speed. Feel free to change the
% number from 100 - it doesn't do anything because it's O(1)
ticfor j=1:1000 if isfield(s,sprintf('p%d',100)) a = s.(sprintf('p%d',100)); endendtoc%%This loop tests the speed of the isKey operation for containers.Maps
% Run it a few times to get a feel for the speed. Feel free to change the% number from 100 - it doesn't do anything because it's O(1). This is
% (surprisingly) slightly slower than the isfield loop above.
ticfor j=1:1000 if isKey(m,sprintf('p%d',100)) a = m(sprintf('p%d',100)); endendtoc%%This loop tests the speed of the isprop operation for MATLAB classes
% Run it a few times to get a feel for the speed. It's massively slower
% than the previous two and gets much slower the more properties one
% adds.
ticfor j=1:1000 if isprop(c,sprintf('p%d',100)) a = c.(sprintf('p%d',100)); endendtoc%%This loop tests the speed of try/catch for MATLAB classes
% Run it a few times to get a feel for the speed. When the name is valid,
% it is about as quick as isfield or isKey. When the name is not (try
% changing to 'p1%d'), it is still faster than isprop, at least in this
% instance.
ticfor j=1:1000 try a = c.(sprintf('p%d',100)); endendtoc
Best Answer