def test_array_vs_getter(self):
setup = '''data = ['a'] * 100\n'''
setup += '''def get(n):\n'''
setup += ''' return data[n]\n'''
setup += '''class B:\n'''
setup += ''' def __getitem__(self, n):\n'''
setup += ''' return data[n]\n'''
setup += '''b = B()\n'''
a = timeit(
'''x = data[5]\n''',
setup=setup,
number=10000)
b = timeit(
'''x = get(5)\n''',
setup=setup,
number=10000)
c = timeit(
'''x = b[5]\n''',
setup=setup,
number=10000)
#print "\n%s %s %s | %s %s" % (a, b, a/b, c, a/c)
# Calling a function or member is significantly slower than direct access.
self.assertGreater(b, a * 1.7)
self.assertGreater(c, a * 2)
评论列表
文章目录