Why is assigning a new handle object in an array slow?
8 views (last 30 days)
Show older comments
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?
Accepted Answer
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.
More Answers (0)
See Also
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!