Input to output variable copies in functions : influence on cpu

6 ビュー (過去 30 日間)
Nicolas Douillet
Nicolas Douillet 2021 年 1 月 28 日
コメント済み: Walter Roberson 2021 年 1 月 28 日
Hi !
One of the advantages of Matlab is its great tolerance on variable names. Meaning you can change the size, the dimension, and even the type of a variable at any time in a script. You can also use the same name for an input and an output variable.
For readability concerns however, when you successively perform a lot of operations on it, it is common (well for me at least) to use for the output variable a different name from the input one. Example :
function var_out = complex_function(var_in)
% Lots of operations on var_in %
% ---------------------------- %
% ---------------------------- %
% ---------------------------- %
var_out = var_in;
end
% or
function var_out = complex_function(var_in)
var_out = var_in;
% Lots of operations on var_out
% ---------------------------- %
% ---------------------------- %
% ---------------------------- %
end
My question is : is is bad in terms of cpu performances to do such copies ? If yes, what is the best compromise in Matlab between code readability and cpu performance concerning variables use and copies ?
I know it looks very basic a question, but then it is as much important to me to clarify its answer.
Thank you for answer !
Best,
Nicolas

採用された回答

Walter Roberson
Walter Roberson 2021 年 1 月 28 日
It does not matter for cpu purposes whether you copy to a variable first and work on the copy, or if you work on the original and copy at the end.
However, in very restricted contexts, there are some cases where
function var_in = complex_function(var_in)
% Lots of operations on var_in %
% ---------------------------- %
% ---------------------------- %
% ---------------------------- %
end
can be faster. Notice the output variable name is the same as the input variable name. When the moon is in the right phase, and the wind is blowing just right, and you are wearing your lucky 5-leaf clover, then this can save making a deep copy of var_in .
  3 件のコメント
Nicolas Douillet
Nicolas Douillet 2021 年 1 月 28 日
Thank you for the link Stephen ! :-)
Walter Roberson
Walter Roberson 2021 年 1 月 28 日
There are additional restrictions not listed in the above link.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by