multi-Singleton-like using __new__

Matt Nordhoff mnordhoff at mattnordhoff.com
Fri Feb 8 19:04:26 EST 2008


J Peyret wrote:
> - Same with using try/except KeyError instead of in cls.cache.
> Has_key might be better if you insist on look-before-you-leap, because
> 'in cls.cache' probably expends to uri in cls.cache.keys(), which can
> be rather bad for perfs if the cache is very big.  i.e. dict lookups
> are faster than scanning long lists.

Not true. 'in' is (marginally) faster than has_key. It's also been
preferred to has_key for a while now.

$ python -m timeit -s "d = dict.fromkeys(xrange(5))" "4 in d"
1000000 loops, best of 3: 0.233 usec per loop
$ python -m timeit -s "d = dict.fromkeys(xrange(5))" "d.has_key(4)"
1000000 loops, best of 3: 0.321 usec per loop
$ python -m timeit -s "d = dict.fromkeys(xrange(500000))" "499999 in d"
1000000 loops, best of 3: 0.253 usec per loop
$ python -m timeit -s "d = dict.fromkeys(xrange(500000))"
"d.has_key(499999)"
1000000 loops, best of 3: 0.391 usec per loop
$ python -m timeit -s "d = dict.fromkeys(xrange(500000))" "1000000 in d"
1000000 loops, best of 3: 0.208 usec per loop
$ python -m timeit -s "d = dict.fromkeys(xrange(500000))"
"d.has_key(1000000)"
1000000 loops, best of 3: 0.324 usec per loop

FWIW, as comparison:

$ python -m timeit -s "l = range(500000)" "0 in l"
10000000 loops, best of 3: 0.198 usec per loop
$ python -m timeit -s "l = range(500000)" "499999 in l"
10 loops, best of 3: 19.8 msec per loop

(Python 2.5.1, Ubuntu. Of course, timings vary a bit, but not much. At
worst, in and has_key are "about the same".)
-- 



More information about the Python-list mailing list