Functions vs scripts: speed
Show older comments
Dear all,
The structure of my code is the following:
** VERSION A**************
output = fun1(inputs)
Piece of code written directly
in the function
end
************************** **** VERSION B **********
output = fun1(inputs)
% The same piece of code is written
% in a script, that is called by the function
run('script1')
end
Both versions give exactly the same results, but version A is much faster. I think version B is better in terms of code readability (I prefer to break the code in smaller chunks), so I would like to know if someone has an idea why version B is slower
Thanks!!
1 Comment
"why version B is slower"
Excluding any possible effects from JIT optimization, it is quite reasonable that B would be slower. Compare:
A:
- search MATLAB path for function file fun1
- run function code
B:
- search MATLAB path for function file fun1
- run function code
- search MATLAB path for script file script1
- run script code using magic run...
Note that scripts should be avoided. Scripts are fun for playing around with, but code that needs to be efficient, testable, and repeatable will use functions (or classes).
Accepted Answer
More Answers (1)
John D'Errico
on 27 Jun 2018
3 votes
Option B is a REALLY bad programming style. It is slow, as you found out. It prevents MATLAB from optimizing your code for efficiency.
In general, learn to avoid scripts. Put the heavy lifting work into functions, although sometimes a mainline script to combine everything together is not a bad thing. What you have here in B is the worst of worlds.
As you learn to write functions, making your code modular, you will be able to reuse code for a variety of problems. That gains on programming time, for your NEXT project. It helps you to debug your code, because you work on one small function at a time. Get each part correct, then worry about the next part.
Is option B better for readability? Why would it be so? Sorry, but not true. Learn to write and use functions. Your code will be better for it, especially as you start to write MODULAR code.
1 Comment
Jan
on 27 Jun 2018
+1. Exactly. Prefer functions. They are nicer, faster, more reliably and easier to debug and to maintain.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!