The dis.dis () function shows that the code object for each version is identical:
aa 1 0 LOAD_CONST 0 (None) 3 RETURN_VALUE localFunc 10 0 LOAD_CONST 0 (None) 3 RETURN_VALUE
So the difference is in the function object. I compared each of the fields (func_doc, func_closure, etc.), and the other is func_globals. In other words, localFunc.func_globals != compiledFunc.func_globals .
There is a cost to providing your own dictionary instead of the built-in global variables (the first should be viewed when a stack frame is created on each call, and on the last you can refer directly to C code that already knows about the standard built-in global dictionary).
This is easy to verify by changing the exec line in your code to:
exec cc in globals(), dd
With which changes, the time difference goes away.
The mystery is solved!
Raymond hettinger
source share