I’ve found two places in the documentation that say that local is better than than global in terms of performance: Performance Tips says
A global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables. Variables should be local, or passed as arguments to functions, whenever possible.
Any code that is performance critical or being benchmarked should be inside a function.
We find that global names are frequently constants, and declaring them as such greatly improves performance.
Similarly, Constants says
The const declaration is allowed on both global and local variables, but is especially useful for globals. It is difficult for the compiler to optimize code involving global variables, since their values (or even their types) might change at almost any time. If a global variable will not change, adding a const declaration solves this performance problem.
Local constants are quite different. The compiler is able to determine automatically when a local variable is constant, so local constant declarations are not necessary for performance purposes.
For interactive sessions in the REPL, I understand how global variables really do need to be kept general, because they could change at any time. But for non-interactive sessions, the distinction between global and local variables seems rather artificial - by placing the entire code inside some function
main and then calling
main from global scope, all global variables can be converted into formally local ones. This would seem to eliminate the performance problems with global variables and with performance-critical code outside of any functions. Why doesn’t Julia do this automatically?