Skip to content

Instantly share code, notes, and snippets.

@pchampin
Last active October 20, 2016 07:06
Show Gist options
  • Save pchampin/38e2a4ac66d6baea44f17a0ce3318293 to your computer and use it in GitHub Desktop.
Save pchampin/38e2a4ac66d6baea44f17a0ce3318293 to your computer and use it in GitHub Desktop.
Comparing performance of comparison operators between different implementation styles in Python
from collections import namedtuple
from timeit import default_timer
from itertools import repeat
class Classic(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __eq__(self, other):
return ((self.a, self.b, self.c) ==
(other.a, other.b, other.c))
def __lt__(self, other):
return ((self.a, self.b, self.c) <
(other.a, other.b, other.c))
class Slotted(object):
__slots__ = ['a', 'b', 'c']
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __eq__(self, other):
return ((self.a, self.b, self.c) ==
(other.a, other.b, other.c))
def __lt__(self, other):
return ((self.a, self.b, self.c) <
(other.a, other.b, other.c))
NamedTuple = namedtuple("NamedTuple", ["a", "b", "c"])
class DerivedNamedTuple(NamedTuple):
def foo(self):
return self.a + self.b
def test_eq(o1, o2):
return o1 == o2
def test_lt(o1, o2):
return o1 < o2
def test(cls):
print(cls.__name__)
if cls is tuple:
cls = lambda *args: tuple(args)
lst = [ cls(3,7,i) for i in range(2000) ]
t0 = default_timer()
for i in lst:
for j in lst:
test_eq(i, j)
t1 = default_timer()
print(" %s" % (t1-t0))
t0 = default_timer()
for i in lst:
for j in lst:
test_lt(i, j)
t1 = default_timer()
print(" %s" % (t1-t0))
test(Classic)
test(Slotted)
test(tuple)
test(NamedTuple)
test(DerivedNamedTuple)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment