⚡️ Speed up function create_bip21_uri by 11%
#149
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.
📄 11% (0.11x) speedup for
create_bip21_uriinelectrum/bip21.py⏱️ Runtime :
2.10 milliseconds→1.88 milliseconds(best of250runs)📝 Explanation and details
The optimization achieves an 11% speedup by eliminating the expensive
urllib.parse.ParseResultconstruction andurlunparse()call, which together accounted for about 7% of the original function's runtime according to the line profiler.Key optimizations:
Eliminated
ParseResultandurlunparse(): Instead of constructing aParseResultobject and callingurlunparse(), the code directly builds the URI string using f-strings. This removes object allocation overhead and the complex URL reconstruction logic.Cached
urllib.parse.quotelookup: By assigningquote = urllib.parse.quoteonce, the code avoids repeated module attribute lookups in the loop processing extra query parameters.Direct string concatenation: The optimized version builds the final URI directly with conditional logic -
f"{BITCOIN_BIP21_URI_SCHEME}:{addr}?{query_str}"when there are query parameters, orf"{BITCOIN_BIP21_URI_SCHEME}:{addr}"when there aren't.Eliminated redundant variable assignment: Removed the intermediate
v = urllib.parse.quote(v)step, directly usingquote(v)in the f-string.Performance impact by test case:
ParseResult/urlunparseoverheadThe function is called from
get_bip21_URI()in the invoices module, which handles payment URI generation. Since this appears to be in a payment processing path, even an 11% improvement in URI generation can meaningfully impact user experience during payment flows.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-create_bip21_uri-mhxwk182and push.