Input to output variable copies in functions : influence on cpu

3 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Walter Roberson
Walter Roberson il 28 Gen 2021
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 Commenti
Walter Roberson
Walter Roberson il 28 Gen 2021
There are additional restrictions not listed in the above link.

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by