Is direct access to a class attribute faster than getting a value through the getter function?

I have embedded code in python. I need to access the attribute of an object.

Performs objectA.attribute_xfaster than objectA.get_attribute_x()?

From an OO point of view, using a getter seems right. But how is computationally cheaper / faster?

+4
source share
2 answers

In most cases object.attribute, this is a simple search for dictionary keys, and object.get_attribute_aa search for a dictionary + any service information when a function is called.

, , , ; properties - ( , , ).

+2

! , , timeit :

from timeit import timeit

class Foo():

    def __init__(self):
        self.bar = "bar"
        self.baz = "baz"

    def get_baz(self):
        return self.baz

print(timeit('foo.bar', setup='import __main__;foo=__main__.Foo()', number=10000000))
print(timeit('foo.get_baz()', setup='import __main__;foo=__main__.Foo()', number=10000000))

:

1.1257502629887313
4.334604475006927

.

+1

Source: https://habr.com/ru/post/1659106/


All Articles