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!