Functions vs scripts: speed
이전 댓글 표시
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
"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).
채택된 답변
추가 답변 (1개)
John D'Errico
2018년 6월 27일
3 개 추천
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
Jan
2018년 6월 27일
+1. Exactly. Prefer functions. They are nicer, faster, more reliably and easier to debug and to maintain.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!