It seems to me that when creating an array of simple handle objects in Matlab time scales about linear. However, if I create exactly the same array and store it as a property of an object, time scales exponentially - so the program gets very slow when many objects are created.
My question is why this is happening and how it can be avoided? Is the pre-allocation for object properties not properly implemented in my code or is there a fundamental problem with the way Matlab handles these things?
I wrote a simple test to illustrate the issue:
Code of simple Object:
classdef SomeSimpleObject < handle
% SomeSimpleObject defines an Object that has one property
properties
property=0;
end
methods
function SimpleObj=SomeSimpleObject()
if nargin~=0
SimpleObj.property=1;
end
end
end
end
Using the following Script to create a 1x10.000 array of these simple objects takes according to the profiler 0,4 sec on my machine:
for n=10000:-1:1 % counting backwards for Memory pre-allocation
ObjectList(n)=SomeSimpleObject();
end
However doing the same thing inside a class constructor and storing the array of 10.000 objects as a property takes 59 sec and it gets much worse quickly. Try it by creating an object from this class (e.g. a=HostingObject)
classdef HostingObject < handle
% This Objects Hosts a List of Objects that are created in the
% constructor
properties
ObjectList=SomeSimpleObject
end
methods
function obj=HostingObject()
for n=10000:-1:1 % counting backwards for Memory pre-allocation
obj.ObjectList(n)=SomeSimpleObject();
end
end
end
end
Searching for an Answer I came across a discussion on Matlab memory allocation and garbage collection. The Answer of Mikhail (also not directly related to my question) made me think that it might be a fundamental problem with the way Matlab implements objects, but I'm still not sure.