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

8 views (last 30 days)
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..

Accepted Answer

Walter Roberson
Walter Roberson on 28 Mar 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 Comments
Walter Roberson
Walter Roberson on 29 Mar 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2014a

Community Treasure Hunt

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

Start Hunting!