Confused about Static class methods versus normal functions, and their speed
14 views (last 30 days)
Show older comments
Jeroen Boschma
on 19 Nov 2015
Commented: Jeroen Boschma
on 19 Nov 2015
Hi all,
Maybe I understand classes wrong, but the following code illustrates the issues I see:
classdef my_class
methods (Access = public, Static = true)
function N = N_intern
N = 3;
end
function N = calc_intern
N = my_class.N_intern;
end
function N = calc_extern
N = N_extern;
end
end
methods (Access = public)
function go(obj)
tic
for i = 1:1e3
obj.calc_intern;
obj.calc_intern;
obj.calc_intern;
obj.calc_intern;
obj.calc_intern;
obj.calc_intern;
obj.calc_intern;
obj.calc_intern;
end
toc
tic
for i = 1:1e3
obj.calc_extern;
obj.calc_extern;
obj.calc_extern;
obj.calc_extern;
obj.calc_extern;
obj.calc_extern;
obj.calc_extern;
obj.calc_extern;
end
toc
end
end
end
function N = N_extern
N = 3;
end
The way I see it:
- From a normal public method, I can call a Static method like obj.calc_intern
- Within calc_intern, I can only call another Static method if I use the classname : my_class.N_intern
Now I have 2 choices if I have a functions that does not use class properties, but clearly belong to the functionality of the class:
- I can make them Static methods, but then I have to use the classname if Static methods call other Static methods.
- I can make them normal functions, outside the class (like N_extern in my example)
In my example, the first option is 3 times slower than the second option. Apparently MATLAB constructs a new class for each call my_class.N_intern? Given the meaning of 'Static' a new instance of the class is not needed I would say...
So for speed considerations you should not use Static methods this way, but simply make them normal functions outside the class. Or am I missing something?
Best regards,
Jeroen
0 Comments
Accepted Answer
Titus Edelhofer
on 19 Nov 2015
Hi Jeroen,
here the MATLAB version used really make a difference: the new engine in R2015b performs much better. On my machine I get:
R2014b:
Elapsed time is 0.143644 seconds.
Elapsed time is 0.090536 seconds.
So roughly factor 1.5.
But with R2015b I get
Elapsed time is 0.003158 seconds.
Elapsed time is 0.003184 seconds.
So both versions MUCH faster, and no overhead for the "intern" any more ...
Titus
More Answers (0)
See Also
Categories
Find more on Construct and Work with Object Arrays 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!