I’ve seen code that looks something like this:
class MyClass:
def __init__(self, someargs):
myObj = OtherClass()
myDict = {}
...code to setup myObj, myDict...
self.myObj = myObj
self.myDict = myDict
My first thought when I saw this was: Why not just use self.myObj and self.myDict in the beginning? It seems inefficient to construct local objects, then assign them to the members. The code to construct the objects do possibly throw exceptions, maybe they did this so it wouldn’t leave a half-constructed object? Do you do this, or just construct the members directly?
It’s faster and more readable to construct the object and then attach it to
self.disassemles to:
You can see that
STORE_ATTRonly gets called once doing it the first way at the end. Doing it the other way,STORE_ATTRstill gets called right at the beginning but nowLOAD_ATTRgets called for every access to the dictionary. The more assignments there are, the higher the cost. Every other instruction is the same. It’s still a ridiculously small cost.This trick can be exploited to make loops with many iterations run faster. It’s not uncommon to see things like
another trick is to pass global functions as default arguments to a function that has a loop like that or gets called a whole bunch to save some attribute lookups: it’s in the local scope which is the first one looked in.
now sum is right in the local scope.