Confused about Static class methods versus normal functions, and their speed
12 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Titus Edelhofer
2015-11-19
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!