Confused about Static class methods versus normal functions, and their speed

12 views (last 30 days)
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:
  1. I can make them Static methods, but then I have to use the classname if Static methods call other Static methods.
  2. 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

Accepted Answer

Titus Edelhofer
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
  1 Comment
Jeroen Boschma
Jeroen Boschma on 19 Nov 2015
Thanks Titus.
This points me in the right direction. I now see that R2015b indeed has a new execution engine, and MathWorks claim to have optimized function call overhead and many OOP things. Apparently it works out very well on this issue. I'll try to find some more in-depth information on their new execution engine.

Sign in to comment.

More Answers (0)

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!