Confused about Static class methods versus normal functions, and their speed
Show older comments
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
Accepted Answer
More Answers (0)
Categories
Find more on Parallel Computing Toolbox 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!