Optimize try/except ordering in sets.py.

Gains a 5:1 speed-up for membership testing by
handling the most common case first (the case
where the element is hashable).

Closes SF Patch 597444.
This commit is contained in:
Raymond Hettinger 2002-08-21 01:35:29 +00:00
parent ede3a0da8b
commit de6d697987
1 changed files with 25 additions and 25 deletions

View File

@ -227,12 +227,12 @@ class BaseSet(object):
(Called in response to the expression `element in self'.) (Called in response to the expression `element in self'.)
""" """
try: try:
transform = element._as_temporarily_immutable return element in self._data
except AttributeError: except TypeError:
pass transform = getattr(element, "_as_temporary_immutable", None)
else: if transform is None:
element = transform() raise # re-raise the TypeError exception we caught
return element in self._data return transform() in self._data
# Subset and superset test # Subset and superset test
@ -369,14 +369,14 @@ class Set(BaseSet):
"""Add all values from an iterable (such as a list or file).""" """Add all values from an iterable (such as a list or file)."""
data = self._data data = self._data
value = True value = True
for elt in iterable: for element in iterable:
try: try:
transform = elt._as_immutable data[element] = value
except AttributeError: except TypeError:
pass transform = getattr(element, "_as_temporary_immutable", None)
else: if transform is None:
elt = transform() raise # re-raise the TypeError exception we caught
data[elt] = value data[transform()] = value
def clear(self): def clear(self):
"""Remove all elements from this set.""" """Remove all elements from this set."""
@ -390,12 +390,12 @@ class Set(BaseSet):
This has no effect if the element is already present. This has no effect if the element is already present.
""" """
try: try:
transform = element._as_immutable self._data[element] = True
except AttributeError: except TypeError:
pass transform = getattr(element, "_as_temporary_immutable", None)
else: if transform is None:
element = transform() raise # re-raise the TypeError exception we caught
self._data[element] = True self._data[transform()] = True
def remove(self, element): def remove(self, element):
"""Remove an element from a set; it must be a member. """Remove an element from a set; it must be a member.
@ -403,12 +403,12 @@ class Set(BaseSet):
If the element is not a member, raise a KeyError. If the element is not a member, raise a KeyError.
""" """
try: try:
transform = element._as_temporarily_immutable del self._data[element]
except AttributeError: except TypeError:
pass transform = getattr(element, "_as_temporary_immutable", None)
else: if transform is None:
element = transform() raise # re-raise the TypeError exception we caught
del self._data[element] del self._data[transform()]
def discard(self, element): def discard(self, element):
"""Remove an element from a set if it is a member. """Remove an element from a set if it is a member.