Why cell arrays and structure consume extra memory?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I observed today that a Matrix , a Cell Array and a Structure with same contents occupy different amount of memory in space and there's a huge difference between them. Why is that? Below is the snippet I executed:
a = {'hello'};
b = 'hello';
c = struct('string' , 'hello');
whos
Name Size Bytes Class Attributes
a 1x1 70 cell
b 1x5 10 char
c 1x1 134 struct
W
0 Kommentare
Antworten (2)
Iain
am 21 Aug. 2014
The memory for a structure needs to contain:
The size of the structure.
The names of the fields.
Something that says "Hey, I'm a structure"
The pointer to the structure
The memory location of each field
Each field needs to contain:
The size of the field
What datatype the field is
The contents of the field (the data, or another field)
A cell array needs to contain:
The pointer to the cell array
The size of the array (I'm 7d, and x by y by z by A by B by C by D).
Something that says "Hey, I'm a cell array"
Each cell needs to contain: The size of the cell contents (I'm 7d, and x by y by z by A by B by C by D).
The type of data in the cell
The contents of the cell (i.e. the data)
An array needs to contain:
The pointer to the array
The size of the array (I'm 7d, and x by y by z by A by B by C by D).
Something that says "Hey, I'm an X format number"
The data
3 Kommentare
Guillaume
am 22 Aug. 2014
Actually,
doc char
"Valid numeric values range from 0 to 65535". chars are 16-bit.
Guillaume
am 21 Aug. 2014
Bearbeitet: Guillaume
am 21 Aug. 2014
Matrices will always use less memory as they only need as much memory as their content will take + memory for the size and type.
If you're familiar with C, a cell array can be considered as an array of pointers to arrays. Thus it needs memory for the main array + its size + its type, plus memory for the sub arrays + their size + their types.
A structure is like a cell array, but in addition it needs memory for the field names.
2 Kommentare
Guillaume
am 22 Aug. 2014
Bearbeitet: Guillaume
am 22 Aug. 2014
I don't know exactly what whos takes into account. it does not appear to report the memory used to store the type and size of the main variable, but the reason cells and structs are bigger are as explained. Cells have an additional level of indirection, thus use more memory and structs also need some space to store the field names (and it looks like whos reports the space used by the pointer to the field name, but not the space used by the field name itself).
Also, note that you can't rely too much on the sizes reported as they won't be the same for 32-bit and 64-bit matlab. For example on my machine (Matlab 64 bit):
whos
Name Size Bytes Class Attributes
a 1x1 122 cell
b 1x5 10 char
c 1x1 186 struct
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!