Walters good points above are not an answer to my question. Let me try to give my point of view on this, and then anyone can feel free to rip it apart. As I said before, I want to be corrected, because I absolutely hate using the global workspace.
However, I believe there are times when using the global workspace is the most efficient. This is both in terms of efficiency of the finished app, as well as development speed and readabillity of code.
the situation occurs with callbacks, for example: GUIs and timer callbacks.
For those applications, there are only 2 ways I know of where you can be guaranteed that no extra copying of data occurrs in Matlab: nested scope variables, and global variables.
Variables created in the topmost function are reacheable to the nested functions below. This requires the entire project to be defined in a single M-file. Starting an application development with efficiency in mind, one may therefore start by making a nested functions solution, and when the size of the M-file grows, one can split up the functions into many files. When multiple files are introduced, with one function per file one need to replace the nested variables. At this point, one can use one out of several ways to make the variables reacheable. There are only two methods that are worth mentioning here, considering effeciency:
- global variables
If the data shared this way is large, and the application will need to modify this data in multiple files, then I believe the following to be true about the global variables solution:
- globals are the most efficient, as in requiring the smallest amount of memory
- globals are the easiest and fastest way to implement the app
This is not an answer to suggest global variables as a good habit of development. If anything, its to point out shortcomings of the language. In Mathworks defence, it seems not a very worthwhile effort to improve this, prior to the introduction of the JIT and copy-on-write functionality. Now that this is in the language, the issues mentioned above can be bottlenecks for efficiency. As a possible future addition to the language... consider something like:
top of the first function:
define workspace myProjSpace
top of all the reliant m-files (the formerly nested functions)
using workspace myProjSpace
A hack I could make is to make a Matlab preprocessing script, that looks for "using workspace" at the top of every file, and then inserts those functions as nested versions into a file that contains "define workspace". This would probably break numerous other things in Matlab, but would work for specific use-cases in callbacks.