Suppose I have some classes foo < handle
, and bar < foo
, baz < foo
, and maybe qux < foo
. There are a couple ways I can store an array of these objects:
As a cell array:
A = {foo bar baz qux} % A(1) would be a cell, A{1} gives me a foo object
Starting with R2011a, I can make
foo <
matlab.mixin.Heterogeneous
, and then build an array directy:A = [foo bar baz qux] % A(1) directly gives me a foo object
The way I see it, from a maintenance perspective it would be better to use the second method rather than the first, this way it removes ambiguity about how to access A
. Namely, when we need to dereference elements of the cell array (cell A(1)
vs foo
object A{1}
, which lives inside A(1)
).
But is there any kind of memory or performance penalty (or benefit) to using one syntax vs the other?
I did a small experiment (source) on the memory and running time of the cell array, containers.Map and a Heterogeneous array. In my method I preallocated each array with N=65535 elements (the max array size for Map and Heterogeneous array), then began assigning each element a uint32, and measured the time and memory. My Heterogeneous Class was a simple class with a single public property, and a constructor which assigned that property. The containers.Map had uint32 key/value pairs.
Immediately note that the size of the mapArray is not accurate. It is hidden behind the containers.Map class implementation, most likley the 112 bytes reported is the memory assigned to the map itself, excluding the data. I approximate the true size to be at minimum (112+65535*(sizeof(uint32)*2)) = 524392 bytes. This value is almost exactly double the hArr size, which makes me think it is quite accurate, since the map must store twice as much data (for key AND value) as the hArr.
The results are straightforward:
I repeated the experiment with N=30 to test for small arrays, the results were similar. God only knows why cells take up so much memory and Heterogeneous arrays are so slow.