Function running slow than scripts when placed in a 'for loop'?

10 ビュー (過去 30 日間)
Angshuman Podder
Angshuman Podder 2020 年 3 月 28 日
コメント済み: Angshuman Podder 2020 年 3 月 31 日
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.
Angshuman Podder
Angshuman Podder 2020 年 3 月 31 日
This is a great answer. thank you so much.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops 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