3

What would be the best way to manage large number of instances of the same class in MATLAB?

Using the naive way produces absymal results:

classdef Request
    properties
        num=7;
    end
    methods
        function f=foo(this)
            f = this.num + 4;
        end
    end
end

>> a=[];  

>> tic,for i=1:1000 a=[a Request];end;toc  

Elapsed time is 5.426852 seconds.  

>> tic,for i=1:1000 a=[a Request];end;toc  
Elapsed time is 31.261500 seconds.  

Inheriting handle drastically improve the results:

classdef RequestH < handle
    properties
        num=7;
    end
    methods
        function f=foo(this)
            f = this.num + 4;
        end
    end
end

>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.097472 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.134007 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.174573 seconds.

but still not an acceptable performance, especially considering the increasing reallocation overhead

Is there a way to preallocate class array? Any ideas on how to manage lange quantities of object effectively?

Thanks,
Dani

3 Answers 3

5

Coming to this late, but would this not be another solution?

a = Request.empty(1000,0); tic; for i=1:1000, a(i)=Request; end; toc;
Elapsed time is 0.087539 seconds.

Or even better:

a(1000, 1) = Request;
Elapsed time is 0.019755 seconds.
Sign up to request clarification or add additional context in comments.

Comments

4

This solution expands on Marc's answer. Use repmat to initialize an array of RequestH objects and then use a loop to create the desired objects:

>> a = repmat(RequestH,10000,1);tic,for i=1:10000 a(i)=RequestH;end;toc
Elapsed time is 0.396645 seconds.

This is an improvement over:

>> a=[];tic,for i=1:10000 a=[a RequestH];end;toc
Elapsed time is 2.313368 seconds.

Comments

2

repmat is your friend:

b = repmat(Request, 1000, 1);

Elapsed time is 0.056720 seconds


b = repmat(RequestH, 1000, 1);
Elapsed time is 0.021749 seconds.

Growing by appending is abysmally slow, which is why mlint calls it out.

2 Comments

The problem: b = repmat(RequestH, 1000, 1); b(1).num=99; b(2).num ans = 99
That's the nature of a handle class. It's fundamentally a singleton class, so all "instances" actually point to a single instance. I was just showing the speedup. Weather to use a Handle class or not is a very separate question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.