Why is assigning a new handle object in an array slow?

I have a handle class that contains an array of node handle objects. Generally I have upwards of 2 million nodes. Initially they're the array is full of pointers to the same sentinel node, and as my algorithm proceeds they're assigned to new node objects. For Example:
classdef SlowExample < handle
properties
foo = Node();
end
methods
function func(obj)
obj.foo(1:2000000) = Node();
for i = 1:800
bar = Node();
obj.foo(i) = bar;
end
end
end
end
In this example I just used a handle class for the nodes:
classdef Node < handle
%NODE a mock object
properties
end
methods
end
end
When run with the profiler, you can see that there is a bottle neck at:
obj.foo(i) = bar;
For me it spent about 300 seconds on that line, and little on anything else. I haven't been able to figure out why. It doesn't seem to happen if foo isn't the data of an object.
Any ideas why this is, and if possible if there's a way to solve it?

댓글 수: 1

Yes, it should be
obj.foo(i) = bar;
Thanks per isakson, I missed that typing it here. The code I ran though didn't have that problem. Also, I'm definitely getting more than that, also using tic and toc as well.
I'm using R2011b, could it be that it's been fixed since my version?

댓글을 달려면 로그인하십시오.

 채택된 답변

per isakson
per isakson 2013년 7월 11일
편집: per isakson 2013년 7월 11일
There is a performance penalty for using objects. That has been discussed here at Answer and in other places, e.g. Considering Performance in Object-Oriented MATLAB Code. The examples, e.g. linked list, in the documentation do not scale. The MathWorks are working on it and the performance has improved with each release. (I use R2012a.)
My execution with the code according to OP
tic
se = SlowExample();
se.func
toc
returns
Elapsed time is 139.794373 seconds.
Modified code, based on a hint (avoid referencing properties in loops) I picked up here at Answer
classdef SlowExample < handle
properties
foo = Node();
end
methods
function func(obj)
fun(1:2000000) = Node();
for i = 1:800
bar = Node();
fun(i) = bar;
end
obj.foo = fun;
end
end
end
Executions time
Elapsed time is 0.188095 seconds.
" upwards of 2 million nodes" I doubt that Matlab is ready for an array of user defined objects that large.
The design approach of Tree data structure as a MATLAB class might be an alternative. It is faster and has potential to be much faster.

댓글 수: 1

Thank you, good to know. Unfortunately, I don't think I'll be able to make that modification, as my code isn't creating the new Nodes all in a loop like that.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Create Custom UI Components에 대해 자세히 알아보기

질문:

2013년 7월 10일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by