MATLAB: Does an object from a handle-inherited class compresses data

handlememoryoop

Take class1 as
classdef class1
properties
prop1 cell = {1};
prop2 string = 'string';
prop3 struct = struct('field1',[1 1],'field2','string');
end
end
The instance obj1 of class1
obj1 = class1
takes 634 bytes of memory (120 bytes for cell + 12 for string + 380 for struct + 112 for ?? = 634). Now take class2 as
classdef class2
properties
prop1
prop2
prop3
end
methods
function out = class2
[out.prop1,out.prop2,out.prop3] = deal(class1);
end
end
end
obj2 being an instance of class2 takes 1902 bytes of memory (634 bytes for each class1 instances * 3 = 1902).
Finally, take class3 inherited from class handle
classdef class3 < handle
properties
prop
end
methods
function out = class3
out.prop = class2;
end
end
end
Now,
obj3 = class3;
takes only 8 bytes, whereas if you store obj3.prop in a variable you'll see that it takes 1902 bytes. My question is, how is this happening? Can I reduce the memory usage by storing my data in objects of this type?

Best Answer

Memory reported for handle classes tends to be totally un-useful. I don't know why, but it always shows up as 8 bytes, but that doesn't mean that is really how much memory is taken up by all its components. I guess that is just the single memory address byte usage for the class 'pointer'. The rest of the memory usage is hidden, or at least I have never found a way within Matlab of seeing my memory usage with handle class objects.