Why does using __slots__ slow down this code?

Viewed 4316

I read in Usage of __slots__? that using __slots__ in Python can actually save time. But, when I tried to find the time taken using datetime, the results were contrary.

import datetime as t

class A():
    def __init__(self,x,y):
        self.x = x
        self.y = y

t1 = t.datetime.now()
a = A(1,2)
t2 = t.datetime.now()
print(t2-t1)

... gave output: 0:00:00.000011 And using slots:

import datetime as t

class A():
    __slots__ = 'x','y'
    def __init__(self,x,y):
        self.x = x
        self.y = y

t1 = t.datetime.now()
a = A(1,2)
t2 = t.datetime.now()
print(t2-t1)

... gave output: 0:00:00.000021

Using slots actually took longer. Why do we need to use __slots__ then?

2 Answers
Related