Speedup: Replace modules and use lazy imports #289
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Checking the import times (see https://medium.com/alan/how-we-improved-our-python-backend-start-up-time-2c33cd4873c8) with:
This test case is when using default Markdown format and the data has been cached.
main
1.014s total: shows importing pytablewriter (0.433s, 42.7%), pkg_resources (0.270s, 26.7%) and httpx (0.243s, 24.0%) are slow.
Use faster PrettyTable for Markdown
Use PrettyTable for default Markdown, use pytablewriter for the more complex formats. Only import each when needed.
We remove 0.433s for pytablewriter but only add 0.011s for PrettyTable.
Down to 0.627s.
Use faster
importlib.metadata
for getting versionInstead of importing
pkg_resources
to get the package version (because we usesetuptools_scm
), use the much fasterimportlib.metadata
(and backport for pre-3.8).https://github.com/pypa/setuptools_scm#retrieving-package-version-at-runtime
We remove 0.272s for
pkg_resources
but only add 0.010s forimportlib.metadata
.Down to 0.378s.
Only import httpx if needed
If we happen to be reading a cached data file, we don't need to import httpx to fetch a new one.
Down to 0.139s.
1.014s -> 0.139s = 7.3x faster.
Another test
= 44x faster per loop.
And another
= 9.5625x faster.