Input to output variable copies in functions : influence on cpu

5 次查看(过去 30 天)
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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating 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