MATLAB Answers

Would passing value to functions be fater than using global variable?

6 views (last 30 days)
Yue
Yue on 18 Mar 2012
I have a data set D of around 5000 data cases. I need to write a iterative function which reads D each iteration (No changes will be made to D ). Around 200-1000 iterations are expected.
I can either
1) Pass D to next function each iteration,
2) Declare D as global variable and access it every iteration.
For this small data set and iteration number probably it doesn't matter, but does anyone have an idea which one of them might in general be faster?
Thanks!

Accepted Answer

Walter Roberson
Walter Roberson on 18 Mar 2012
Passing the variable should be faster.
Values are passed in a way that only requires passing the address of the value and no copy of the value will be made in the routine unless the routine modifies that variable.
On the other hand, "global" has some overhead every time it is encountered, because the symbol table of the global workspace has to be searched at execution time. If the symbol is not found in the global workspace then it has to be created in the global workspace and initialized to the empty matrix. Then the descriptor of the symbol that was found or the descriptor of the newly-created symbol has to be imported to the function workspace, marked so that the original memory will not be cleared when the function returns. Even if it is the only global you have, all of this costs overhead that is not present for a variable that is passed in.
  3 Comments
Walter Roberson
Walter Roberson on 18 Mar 2012
Thanks, James. It sounds like a bit of a wonder that it all works ;-)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by