Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
leopoodle Avatar asked Oct 27 '16 18:10

leopoodle


People also ask

Are direct access slower than getters?

Getters and setters are essentially sugar-coated wrappers for methods. So it's going to be slower than directly accessing something.

When should you use a class attribute?

The class attribute specifies one or more classnames for an element. The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.

What is the more pythonic way to use getters and setters?

Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.

What happens when Python properties are accessed directly?

Return Value: Thus, the name property hides the private instance attribute __name . The name property is accessed directly, but internally it will invoke the getname() or setname() method, as shown below. As you can see above, the getname() method gets called automatically when we access the name property.


1 Answers

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.

like image 112
tdelaney Avatar answered Sep 23 '22 03:09

tdelaney