[Python-ideas] set.add(x) slower than if x in set:set.add(x)

Nick Coghlan ncoghlan at gmail.com
Mon Sep 14 22:44:58 CEST 2009


Gerald Britton wrote:
> Aha ok, so cheap inserts, not so cheap lookups (especially if not found)

Other way around - lookup is cheap (unless you have an expensive hash
calculation or poor hash diversity), addition can be more expensive
(although the set C implementation is optimised pretty well).

Note that this does mean the relative benefits of the LBYL
(Look-Before-You-Leap) approach and the EAFP
(Easier-to-Ask-Forgiveness-than-Permission) approach vary based on the
data types involved. I would get different performance numbers using
strings or floats or Decimal objects rather than ints because the
relative cost of the hash() calculation would change.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list