⚡️ Speed up function get_best_encoding
by 167%
#42
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.
📄 167% (1.67x) speedup for
get_best_encoding
insrc/click/_compat.py
⏱️ Runtime :
73.7 microseconds
→27.6 microseconds
(best of57
runs)📝 Explanation and details
Here is a rewritten version of the program that optimizes the performance using some minor improvements.
Explanation
Local Variable for Encoding.
We use a local variable
encoding
instead ofrv
. This saves unnecessary recalculation and provides slightly better readability.Removed
is_ascii_encoding
Call.The check
if is_ascii_encoding(rv):
has been replaced directly byif encoding == "ascii":
, because the lookup inis_ascii_encoding
function would ideally get the name directly from its input, meaning any discrepancies due to varying formats aren't relevant in the specific case of handling "ascii". This removes one function call, making the code a bit faster.By making these changes, the function
get_best_encoding
should now run slightly faster, as it reduces the number of function calls and unnecessary assignments.✅ Correctness verification report:
🌀 Generated Regression Tests Details
📢 Feedback on this optimization?