Created
November 12, 2019 21:12
-
-
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.
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
# 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) |
Author
commadelimited
commented
Nov 12, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment