Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Matlab taking exponential time when creating a handle object array as an object property

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.

like image 380
Jacob Avatar asked Oct 11 '11 13:10

Jacob


1 Answers

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.

like image 127
Jonas Heidelberg Avatar answered Oct 17 '22 09:10

Jonas Heidelberg