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.
I don't know why your code is slow, but I found a way to fix it: use a cell array instead of a normal array. I don't find it completely intuitive myself, but here are my profiling results:
>> tic,a=HostingObject;toc
Elapsed time is 105.320128 seconds.
>> tic,a=JonasHostingObject;toc
Elapsed time is 2.394570 seconds.
The object is defined as follows:
classdef JonasHostingObject < handle
properties
ObjectList
end
methods
function obj=JonasHostingObject()
obj.ObjectList=cell(10000,1);
for n=1:10000
obj.ObjectList{n}=SomeSimpleObject();
end
end
end
end
I'm using MATLAB R2011a 64bit, in case it matters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With