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

7 views (last 30 days)
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
James Tursa
James Tursa on 18 Mar 2012
"... requires passing the address of the value ..."
Sort of. Generally, when passing a variable to an m-function a shared data copy is typically passed. So header information for a new variable is created for each argument (but the data itself is not copied unless the routine modifies it as you state). When passing a variable to a mex function the address of the original is typically passed in (not a shared data copy). There are exceptions to this (e.g., scalar variables in some contexts are passed as a deep copy not a shared data copy, and cell and struct elements are typically passed in as shared data copies even to mex functions).
The above in FYI only, and does not invalidate Walter's suggestion that globals are typically slower (at least, that has been my experience).
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!