Last active
March 3, 2023 11:17
-
-
Save nphilipp/6c4400f97eac7258568e38fb939d84ab to your computer and use it in GitHub Desktop.
Benchmark try/except vs. conditionals for caching (short-lived objects)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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