Skip to content

Instantly share code, notes, and snippets.

@nphilipp
Last active March 3, 2023 11:17
Show Gist options
  • Save nphilipp/f211c8a016a8057e7f4b89f6b5530714 to your computer and use it in GitHub Desktop.
Save nphilipp/f211c8a016a8057e7f4b89f6b5530714 to your computer and use it in GitHub Desktop.
Benchmark try/except vs. conditionals for caching (long-lived objects)
#!/usr/bin/env python
import timeit
class Foo:
base_url = "http://boo"
def __str__(self):
try:
return self._str
except AttributeError:
clsname = type(self).__name__
self._str = f"{clsname}({self.base_url!r})"
return self._str
class Bar:
base_url = "http://boo"
def __str__(self):
if hasattr(self, "_str"):
return self._str
clsname = type(self).__name__
self._str = f"{clsname}({self.base_url!r})"
return self._str
class Baz:
base_url = "http://boo"
def __str__(self):
if not hasattr(self, "_str"):
clsname = type(self).__name__
self._str = f"{clsname}({self.base_url!r})"
return self._str
foo = Foo()
bar = Bar()
baz = Baz()
print("foo:", timeit.Timer(stmt="str(foo)", globals=locals()).timeit())
print("bar:", timeit.Timer(stmt="str(bar)", globals=locals()).timeit())
print("baz:", timeit.Timer(stmt="str(baz)", globals=locals()).timeit())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment