TL;DR: No. containers.Map
has uses that cannot be replaced with a table
. And I would not choose a table
for a dictionary.
containers.Map
and table
have many differences worth noting. They each have their use. A third container we can use to create a dictionary is a struct
.
To use a table
as a dictionary, you'd define only one column, and specify row names:
T = table(data,'VariableNames',{'value'},'RowNames',names);
Here are some notable differences between these containers when used as a dictionary:
Speed: The struct
has the fastest access by far (10x). containers.Map
is about twice as fast as a table
when used in an equivalent way (i.e. a single-column table with row names).
Keys: A struct
is limited to keys that are valid variable names, the other two can use any string as a key. The containers.Map
keys can be scalar numbers as well (floating-point or integer).
Data: They all can contain heterogeneous data (each value has a different type), but a table
changes how you index if you do this (T.value(name)
for homogeneous data, T.value{name}
for heterogeneous data).
Syntax: To lookup the key, containers.Map
provides the most straight-forward syntax: M(name)
. A table
turned into a dictionary requires the pointless use of the column name: T.value(name)
. A struct
, if the key is given by the contents of a variable, looks a little awkward: S.(name)
.
Construction: (See the code below.) containers.Map
has the most straight-forward method for building a dictionary from given data. The struct
is not meant for this purpose, and therefore it gets complicated.
Memory: This is hard to compare, as containers.Map
is implemented in Java and therefore whos
reports only 8 bytes (i.e. a pointer). A table
can be more memory efficient than a struct
, if the data is homogeneous (all values have the same type) and scalar, as in this case all values for one column are stored in a single array.
Other differences:
A table
obviously can contain multiple columns, and has lots of interesting methods to manipulate data.
A stuct
is actually a struct array, and can be indexed as S(i,j).(name)
. Of course name
can be fixed, rather than a variable, leading to S(i,j).name
. Of the three, this is the only built-in type, which is the reason it is so much more efficient.
Here is some code that shows the difference between these three containers for constructing a dictionary and looking up a value:
% Create names
names = cell(1,100);
for ii=1:numel(names)
names{ii} = char(randi(+'az',1,20));
end
name = names{1};
% Create data
values = rand(1,numel(names));
% Construct
M = containers.Map(names,values);
T = table(values.','VariableNames',{'value'},'RowNames',names);
S = num2cell(values);
S = [names;S];
S = struct(S{:});
% Lookup
M(name)
T.value(name)
S.(name)
% Timing lookup
timeit(@()M(name))
timeit(@()T.value(name))
timeit(@()S.(name))
Timing results (microseconds):
M: 16.672
T: 23.393
S: 2.609