Filter löschen
Filter löschen

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

6 Ansichten (letzte 30 Tage)
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..

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 28 Mär. 2020
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 Kommentare
Walter Roberson
Walter Roberson am 29 Mär. 2020
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 am 31 Mär. 2020
This is a great answer. thank you so much.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by