The example below is from a REST database driver on Python 2.7.
In the __setattr__
method below, if I use the commented out getattr()
line, it reduces the object instantiation performance from 600 rps to 230.
Why is getattr()
so much slower than self.__dict__.get()
in this case?
class Element(object):
def __init__(self, client):
self._client = client
self._data = {}
self._initialized = True
def __setattr__(self, key, value):
#_initialized = getattr(self, "_initialized", False)
_initialized = self.__dict__.get("_initialized", False)
if key in self.__dict__ or _initialized is False:
# set the attribute normally
object.__setattr__(self, key, value)
else:
# set the attribute as a data property
self._data[key] = value
self.__dict__
in a local variable - even for only two access to it. (dict_ = self.__dict__
at the start of__setattr__
) – Coquille