Created
April 1, 2021 08:40
-
-
Save jace/12c878a6d8ce1f799315fa54999bbe5c to your computer and use it in GitHub Desktop.
This file contains 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
# Performance test for coaster.sqlalchemy.registry.InstanceRegistry | |
import timeit | |
class Registry: | |
def __init__(self, param=None): | |
self.param = param | |
class Namespacer1: | |
def __init__(self, registry, obj): | |
self.__registry = registry | |
self.__obj = obj | |
self.__param = registry.param | |
def __getattr__(self, attr): | |
if self.__param is not None: | |
return (self.__registry, self.__obj, self.__param) | |
else: | |
return (self.__registry, self.__obj) | |
class Namespacer2: | |
def __init__(self, registry, obj): | |
self.__registry = registry | |
self.__obj = obj | |
def __getattr__(self, attr): | |
if self.__registry.param is not None: | |
return (self.__registry, self.__obj, self.__registry.param) | |
else: | |
return (self.__registry, self.__obj) | |
class Namespacer3: | |
def __init__(self, registry, obj): | |
self.__registry = registry | |
self.__obj = obj | |
def __getattr__(self, attr): | |
param = self.__registry.param | |
if param is not None: | |
return (self.__registry, self.__obj, param) | |
else: | |
return (self.__registry, self.__obj) | |
r1 = Registry('obj') | |
r2 = Registry() | |
if __name__ == '__main__': | |
# Performance, fastest to slowest: | |
# 3 (local var), 2 (namespaced access), 1 (instance var) | |
print(timeit.timeit('a = Namespacer3(r2, r2); a.x', globals=globals())) | |
print(timeit.timeit('a = Namespacer2(r2, r2); a.x', globals=globals())) | |
print(timeit.timeit('a = Namespacer1(r2, r2); a.x', globals=globals())) | |
print(timeit.timeit('a = Namespacer3(r1, r1); a.x', globals=globals())) | |
print(timeit.timeit('a = Namespacer2(r1, r1); a.x', globals=globals())) | |
print(timeit.timeit('a = Namespacer1(r1, r1); a.x', globals=globals())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output: