Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduardoluizgs/b506b2a5ccc55a98cfaf0c543206dee0 to your computer and use it in GitHub Desktop.
Save eduardoluizgs/b506b2a5ccc55a98cfaf0c543206dee0 to your computer and use it in GitHub Desktop.
Performance Comparison of namedtuple, namedlist, and recordclass
import sys
class Record(object):
__slots__ = ()
def __init__(self, *args):
assert len(self.__slots__) == len(args)
for field, value in zip(self.__slots__, args):
setattr(self, field, value)
def __getitem__(self, index):
return getattr(self, self.__slots__[index])
def __len__(self):
return len(self.__slots__)
def __eq__(self, that):
if not isinstance(that, type(self)):
return NotImplemented
return all(item == iota for item, iota in zip(self, that))
def __repr__(self):
args = ', '.join(repr(item) for item in self)
return '%s(%s)' % (type(self).__name__, args)
def __getstate__(self):
return tuple(self)
def __setstate__(self, state):
self.__init__(*state)
from collections import namedtuple
from namedlist import namedlist
from recordclass import recordclass
NTTest = namedtuple('NTTest', 'a b c d e f')
NLTest = namedlist('NLTest', 'a b c d e f')
RCTest = recordclass('RCTest', 'a b c d e f')
class RETest(Record):
__slots__ = 'a', 'b', 'c', 'd', 'e', 'f'
nttest = NTTest(1, 2, 3, 4, 5, 6)
nltest = NLTest(1, 2, 3, 4, 5, 6)
rctest = RCTest(1, 2, 3, 4, 5, 6)
retest = RETest(1, 2, 3, 4, 5, 6)
print 'Attribute Access'
print 'namedtuple'
%timeit nttest.c
print 'namedlist'
%timeit nltest.c
print 'recordclass'
%timeit rctest.c
print 'Record'
%timeit retest.c
print 'Object Size'
print 'namedtuple'
print sys.getsizeof(nttest)
print 'namedlist'
print sys.getsizeof(nltest)
print 'recordclass'
print sys.getsizeof(rctest)
print 'Record'
print sys.getsizeof(retest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment