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

8 views (last 30 days)
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 Comment
Yasha
Yasha on 11 Jul 2013
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?

Sign in to comment.

Accepted Answer

per isakson
per isakson on 11 Jul 2013
Edited: per isakson on 11 Jul 2013
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 Comment
Yasha
Yasha on 11 Jul 2013
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!