3 ms·
At the risk of exposing my ignorance, I thought >Other “common wisdom”, like using locals instead of globals, yields relatively little gain. this advice was t
by phren0logy 15y ago
At the risk of exposing my ignorance, I thought
>Other “common wisdom”, like using locals instead of globals, yields relatively little gain.
this advice was typically more related to avoiding collisions with variable names, rather than performance?
- thristian 15y agoIn Python, it's both - the basic structured-programming advice to avoid global variables is always good, but it's a specific quirk of Python that makes global variables (including built-in functions) slower than local variables. Python has full dynamic scoping, which means that inside a function you can refer to any variables set in outer scopes. Because Python is a dynamic language, every time you refer to a variable, the Python interpreter looks for it in the local scope first, and then each enclosing scope until it hits the containing module. A local variable will always be found in the first iteration of that loop, a global variable will take at least two iterations.
- adgar 15y ago> Python has full dynamic scoping, which means that inside a function you can refer to any variables set in outer scopes. You are describing lexical scope, not dynamic scope.
- encukou 15y agoAnother CPython quirk is that global (module-level) variables are looked up in a dict, but a function's local variables normally get a reserved chunk of memory that's directly indexable.
- lloeki 15y agoA "global" variable is one that is not residing in the local scope. Global here is really non-local, which is a term that changed during the py3k transition. As you see, str and ord are "system" functions, but really are variables containing function objects. The same goes for WHITELIST, which is a variable (conventionally named as a constant) probably defined at the module level. All of those are not local to the function, hence more taxing to call in a loop. Besides, the general advice is not to avoid collisions (you use both namespaces and locality to resolve that) as the non local stuff here really has a reason to be global, but non local stuff has to survive concurrency. It is the case here as the things called really are constants.