[Python-3000] Set literal

Guido van Rossum guido at python.org
Fri Jan 25 06:17:38 CET 2008

Thanks! I tried it again with a 2-element tuple and frozenset, and
with hits on the first and second item, and with a miss. I am
convinced. Even for a 2-element set, the frozenset comes out ahead
except compared to a hit on the first tuple item. So let's leave this
alone -- if the user writes a tuple, we use a tuple (because the
semantics are different), if the user writes a frozenset literal, we
use that.


On Jan 24, 2008 9:09 PM, John Barham <jbarham at gmail.com> wrote:
> 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 (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
> _______________________________________________
> Python-3000 mailing list
> Python-3000 at python.org
> http://mail.python.org/mailman/listinfo/python-3000
> Unsubscribe: http://mail.python.org/mailman/options/python-3000/guido%40python.org

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-3000 mailing list