Ví dụ bên dưới là từ trình điều khiển cơ sở dữ liệu REST trên Python 2.7.Tại sao getattr() chậm hơn nhiều so với bản thân .__ dict __. Get()?
Trong __setattr__
phương pháp dưới đây, nếu tôi sử dụng các nhận xét ra getattr()
dòng, nó làm giảm các đối tượng instantiation hiệu suất từ 600 rps để 230.
Tại sao getattr()
nên chậm hơn nhiều so với self.__dict__.get()
trong trường hợp này?
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
Trên một lưu ý phụ, nếu bạn đang có sự khác biệt về hiệu suất, hãy lưu vào bộ nhớ cache 'self .__ dict__' trong biến cục bộ - ngay cả khi chỉ có hai quyền truy cập vào nó. ('dict_ = self .__ dict__' khi bắt đầu' __setattr__') – jsbueno