[three]Bean

python's dir() is a (big) bottleneck

Apr 29, 2011 | categories: python View Comments

Wrote this up due to this commit to tw2.core.

(EDIT: Thanks to lmacken for the tip on iteritems().)

#!/usr/bin/env python
""" Experiment showing that :func:`dir` is a bottleneck.

Expected output:
    1.384130 [getattr(obj, k) for k in dir(obj)]
    0.343161 [v for k, v in obj.__dict__.items()]
    0.278336 [v for k, v in obj.__dict__.iteritems()]
"""

from timeit import Timer

statements = [
    "[getattr(obj, k) for k in dir(obj)]",
    "[v for k, v in obj.__dict__.items()]",
    "[v for k, v in obj.__dict__.iteritems()]",
]

for stmt in statements:
    print "%.6f" % Timer(stmt, "import os as obj").timeit(10000), stmt
View Comments
blog comments powered by Disqus