leopoodle
leopoodle

Reputation: 2482

Is directly accessing class attribute faster than getting the value via a getter function?

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

Is doing objectA.attribute_x faster than objectA.get_attribute_x()?

From OO point of view, using the getter seems the right thing to do. But which way is computationally cheaper/faster?

Upvotes: 6

Views: 2162

Answers (2)

tdelaney
tdelaney

Reputation: 77337

Lets find out! It seems like there is more work with the function call, but lets let timeit have a crack at it:

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))

On one run on my computer I got:

1.1257502629887313
4.334604475006927

Direct attribute lookup is the clear winner.

Upvotes: 3

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160407

In most cases, object.attribute is a simple dictionary key look-up while object.get_attribute_a is a dictionary look-up + any overhead of calling the function.

So yes, the function version is slower and generally not used in the form you're used to; properties are the standard way of managing attributes (and again, the fact that they manage the attribute before returning makes them slower).

Upvotes: 2

Related Questions