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..

采纳的回答

Walter Roberson
Walter Roberson 2020-3-28
Generally speaking:
  • 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
  3 个评论
Walter Roberson
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2014a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by