Ecir Hana
Ecir Hana

Reputation: 11468

Python class variable access speed

Say there is a class:

class x(obj):
    y = 1

What is faster (or preferred):

    def __init__(self):
        print self.y

or:

    def __init__(self):
        print x.y

I assume x.y better communicates the intend but I'm interested in the speed implications.

Upvotes: 0

Views: 1492

Answers (2)

Nicolas Barbey
Nicolas Barbey

Reputation: 6797

Note that depending on the class implementation the returned values may differ.

This returns the y attribute of the instance :

def __init__(self):
    print self.y

While this returns the y attribute of the class :

def __init__(self):
    print x.y

If the constructor override the y attribute a la :

def __init__(self, y=None):
    self.y = y
def print(self):
    print self.y

the returned values will differ. Python looks up the instance internal dictionary checking for y before to check for the class internat dictionary. So I think that print x.y should be slightly faster because it avoids looking up the instance dictionary.

Upvotes: 0

phihag
phihag

Reputation: 287825

The performance gain you could possibly achieve with these micro optimizations doesn't matter. The impact of the printing dwarfs the cost of attribute access by far. For reference, here's a test script:

import sys,timeit
class ClassAccess(object):
    y = 1
    def __init__(self):
        print(ClassAccess.y)

class SelfAccess(object):
    y = 1
    def __init__(self):
        print(self.y)

ca = timeit.timeit(ClassAccess, number=100000)
sa = timeit.timeit(SelfAccess, number=100000)

sys.stderr.write(str(ca) + "\n")
sys.stderr.write(str(sa) + "\n")

On my machine (with the yakuake terminal), this outputs

0.640013933182
0.628859043121

This is within experimental error of both variants being identical. Crude experimentation shows that:

  • Approximately 90% of the runtime is caused by actually displaying the printed result.
  • Of the rest, approximately 50% is the time that the print statement alone takes up.
  • Approximately 80% of the rest of that is caused by the allocation of the objects.

Therefore, it's safe to say to derive the conclusion that there is no difference in performance.

Upvotes: 3

Related Questions