Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid Matlab taking exponential time when creating a handle object array as an object property
    primarykey
    data
    text
    <p>It seems to me that when creating an <strong>array of simple handle objects in Matlab time scales about linear</strong>. However, if I create exactly the same array and <strong>store it as a property of an object, time scales exponentially</strong> - so the program gets very slow when many objects are created.</p> <p><strong>My question is why this is happening and how it can be avoided?</strong> 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?</p> <p>I wrote a simple test to illustrate the issue:</p> <p><strong>Code of simple Object:</strong></p> <pre><code>classdef SomeSimpleObject &lt; 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 </code></pre> <p><strong>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:</strong></p> <pre><code>for n=10000:-1:1 % counting backwards for Memory pre-allocation ObjectList(n)=SomeSimpleObject(); end </code></pre> <p><strong>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. <em>a=HostingObject</em>)</strong></p> <pre><code>classdef HostingObject &lt; 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 </code></pre> <p>Searching for an Answer I came across a discussion on Matlab memory allocation and <a href="https://stackoverflow.com/questions/1446281/matlabs-garbage-collector">garbage collection</a>. 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload