Skip to content

Instantly share code, notes, and snippets.

@commadelimited
Created November 12, 2019 21:12
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 commadelimited/65dc31f8832859d5838c7feb13c5d472 to your computer and use it in GitHub Desktop.
Save commadelimited/65dc31f8832859d5838c7feb13c5d472 to your computer and use it in GitHub Desktop.
Test the time difference between directly accessing properties on a nested object, vs saving an intermediate variable.
# importing the required module
import timeit
# code snippet to be executed only once
setup = """
class FauxClass(object):
pass
page = FauxClass()
page.url = 'the url'
page.owner = FauxClass()
page.owner.name = 'the name'
"""
# direct property access
code_01 = """
temp = '{name} published {url}'.format(
name=page.owner.name,
url=page.url,
)
"""
# intermediate variable
code_02 = """
owner = page.owner
temp = '{name} published {url}'.format(
name=owner.name,
url=page.url,
)
"""
# timeit statement
print timeit.timeit(setup=setup, stmt=code_01, number=100000)
print timeit.timeit(setup=setup, stmt=code_02, number=100000)
@commadelimited
Copy link
Author

$ python timing.py
0.0514490604401
0.0502469539642

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment