Skip to content

Instantly share code, notes, and snippets.

@nphilipp
Last active March 3, 2023 11:17
Show Gist options
  • Save nphilipp/6c4400f97eac7258568e38fb939d84ab to your computer and use it in GitHub Desktop.
Save nphilipp/6c4400f97eac7258568e38fb939d84ab to your computer and use it in GitHub Desktop.
Benchmark try/except vs. conditionals for caching (short-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
print(
"foo:",
timeit.Timer(stmt="foo = Foo(); str(foo)", globals=locals()).timeit(),
)
print(
"bar:",
timeit.Timer(stmt="bar = Bar(); str(bar)", globals=locals()).timeit(),
)
print(
"baz:",
timeit.Timer(stmt="baz = Baz(); str(baz)", globals=locals()).timeit(),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment