- functions have more opportunities for internal acceleration than scripts have
- but function calls have overhead
- if the work being done inside the function is low compared to the function call overhead, then the function could be slower
Function running slow than scripts when placed in a 'for loop'?
조회 수: 8 (최근 30일)
이전 댓글 표시
I am trying to execute a program which has a function being called in a for loop, say:
%version1
for i =1 : 1000
x = myfunc1(a,b,c);
y = myfunc2(d,e,f);
[m,n,o] = myfunc(x,y);
end
Now, when I code the same goal in a different way using scripts like:
%version2
for i =1 : 1000
x = a + b + c; %function is more complicated
y = d + e + f; %function is more complicated
m = x*y; %function is more complicated
n = x*x*y; %function is more complicated
o = x*y*y; %function is more complicated
end
Version 2 is 3x faster than version 1 while both give same values. Why is that happening? When to use scripts and when to use functions in a generic sense?
Thanks..
댓글 수: 0
채택된 답변
Walter Roberson
2020년 3월 28일
Generally speaking:
댓글 수: 3
Walter Roberson
2020년 3월 29일
If you have to do an algorithm multiple times and each time is defined as having to be exactly the same algorithm as the other times, then you should use a function, unless you can prove that your algorithm is the fastest approach and that the function call overhead is making the difference between your code being usable or not.
If you have an algorithm that you are going to use in multiple programs, then you should probably use a function (or class)
If you have imposed coding style requirements such as it being mandatory that every function be at most 50 lines long, then you should use a function.
When not to use a function? When the code is fairly simple and short and it is clearer to see it inline instead of mentally having to space over to a function. For example you would seldom write a function for 2*x+1.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!