[Python-3000] Set literal
John Barham
jbarham at gmail.com
Fri Jan 25 06:09:03 CET 2008
Guido wrote:
> (I suspect for a 2-element set of ints or strings, translating "x in
> {C1, C2}" into "x in (C1, C2)" might actually be a slight win since
> probing a tuple must be much faster than probing a set; but that's a
> detail.)
A trivial but hopefully fairly representative benchmark:
ActivePython 2.5.1.1 (ActiveState Software Inc.) based on
Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer("3 in (1,2,3)").timeit()
0.20900340099335493
>>> timeit.Timer("3 in frozenset((1,2,3))").timeit()
0.72151788129635008
>>> timeit.Timer("3 in choices", setup="choices = (1,2,3)").timeit()
0.21716441294536537
>>> timeit.Timer("3 in choices", setup="choices = frozenset((1,2,3))").timeit()
0.16064769736693307
This demonstrates that constructing a frozen set obviously takes
longer, but suggests that searching even within a 3-element set (the
construction time for which could presumably be amortized away by the
compiler) is quicker than in a tuple, which is heartening. So the
only overhead for using frozen sets is slightly more memory...
John
More information about the Python-3000
mailing list