Initializing an Array of Handle Objects - Memory Usage inefficient?
Show older comments
Assuming the following example handle class with 19 properties and a default constructor is given:
classdef MyClass < handle
properties
property1
property2
property3
property4
property5
property6
property7
property8
property9
property10
property11
property12
property13
property14
property15
property16
property17
property18
property19
end
methods
function obj = MyClass()
obj.property1 = 0;
obj.property2 = 0;
obj.property3 = 0;
obj.property4 = 0;
obj.property5 = 0;
obj.property6 = 0;
obj.property7 = 0;
obj.property8 = 0;
obj.property9 = 0;
obj.property10 = 0;
obj.property11 = 0;
obj.property12 = 0;
obj.property13 = 0;
obj.property14 = 0;
obj.property15 = 0;
obj.property16 = 0;
obj.property17 = 0;
obj.property18 = 0;
obj.property19 = 0;
end
end
end
Using now the command:
handlearray(1,1800000) = MyClass;
creates now an [1,1800000]-size array of handle objects. I know that Matlab is using Copy on Write. Therefore such a initialization results in two calls to the class constructor. The first creates the object for array element handlearray(1,1800000). The second creates a default object that Matlab copies to all remaining empty array elements. The memory usage for such an initialization is 1,3GB RAM.
Running now following code, all 19 properties of all objects are reassigned with the same value 0.
Code:
for i=1:size(handlearray,2)
handlearray(1,i).property1 = 0;
handlearray(1,i).property2 = 0;
handlearray(1,i).property3 = 0;
handlearray(1,i).property4 = 0;
handlearray(1,i).property5 = 0;
handlearray(1,i).property6 = 0;
handlearray(1,i).property7 = 0;
handlearray(1,i).property8 = 0;
handlearray(1,i).property9 = 0;
handlearray(1,i).property10 = 0;
handlearray(1,i).property11 = 0;
handlearray(1,i).property12 = 0;
handlearray(1,i).property13 = 0;
handlearray(1,i).property14 = 0;
handlearray(1,i).property15 = 0;
handlearray(1,i).property16 = 0;
handlearray(1,i).property17 = 0;
handlearray(1,i).property18 = 0;
handlearray(1,i).property19 = 0;
end
With this code/script the actual memory block allocation has been done. My needed memory goes from 1,3GB to 7,3GB RAM.
Assuming the properties are of type double, the needed amount of storage for the data is something around:
1 double property --> 8 Bytes
19*8 Bytes per Object
1800000 Objects
total needed amount = 1800000*19*8 Bytes = 273.6 MB
Accounting also the needed space for pointers, type and so on that should be an additional 30MB.
Why does Matlab need 7.3GB RAM to store 273.6MB of data?
Assuming there is no way around using an object-oriented-programming solution, how do I reduce this needed amount without changing the class too much?
Greetings, Artur G.
Answers (0)
Categories
Find more on Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!