Skip to content

Instantly share code, notes, and snippets.

@andriykohut
Created August 29, 2018 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriykohut/a64f2c1acda3eadf699989c021e7bfa5 to your computer and use it in GitHub Desktop.
Save andriykohut/a64f2c1acda3eadf699989c021e7bfa5 to your computer and use it in GitHub Desktop.
Component resolution performance
from tornado.httpclient import HTTPRequest
import timeit
from collections import deque
class View:
pass
class Ctx:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class Component:
def __init__(self, name):
self.name = name
self.view = View()
def resolve(self, ctx):
self.view.x = ctx.x
self.view.y = ctx.y
self.view.a, self.view.b = ctx.z['x'], ctx.z['y']
self.view.req = ctx.req
def _get_child_components(c):
for attr in vars(c.view).values():
if isinstance(attr, Component):
yield attr
elif isinstance(attr, list):
for i in attr:
if isinstance(i, Component):
yield i
def resolve_deque(component, ctx):
to_visit = deque([component])
while to_visit:
c = to_visit.popleft()
c.resolve(ctx)
for c in _get_child_components(c):
to_visit.append(c)
def resolve_list(component, ctx):
to_visit = [component]
while to_visit:
c = to_visit[0]
c.resolve(ctx)
to_visit = to_visit[1:]
for c in _get_child_components(c):
to_visit.append(c)
def resolve_recursive(component, ctx):
component.resolve(ctx)
for c in _get_child_components(component):
resolve_recursive(c, ctx)
class A(Component):
def resolve(self, ctx):
self.view.x = 1
self.view.one = Component('one')
self.view.two = Component('two')
self.view.three = Component('three')
self.view.four = Component('four')
self.view.two.view.x = Component("two_nested")
self.view.two.view.x.view.y = Component("two_nested_nested")
self.view.items = [Component("1"), Component("2")]
self.view.items[0].view.x = Component("1_nested")
self.view.items[1].view.x = Component("2_nested")
if __name__ == '__main__':
ctx = Ctx(x=1, y=2, z={'x': 1, 'y': 2}, req=HTTPRequest('http://test.com'))
print("Deque:")
print(timeit.timeit("resolve_deque(A('a'), ctx)", globals=globals(), number=100000))
print("List:")
print(timeit.timeit("resolve_list(A('a'), ctx)", globals=globals(), number=100000))
print("Recursive:")
print(timeit.timeit("resolve_recursive(A('a'), ctx)", globals=globals(), number=100000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment