⚡️ Speed up method SigningKey.to_string by 20%
#72
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.
📄 20% (0.20x) speedup for
SigningKey.to_stringinpython/ccxt/static_dependencies/ecdsa/keys.py⏱️ Runtime :
2.25 milliseconds→1.87 milliseconds(best of115runs)📝 Explanation and details
The optimization replaces inefficient string formatting operations with Python's built-in
hex()function andzfill()method, delivering a 20% speedup.Key Changes:
"%0" + str(2 * l) + "x"andfmt_str % numwithhex(num)[2:].zfill(2 * l).encode()call sincehex()already returns a string that can be directly used withbinascii.unhexlify()Why This is Faster:
hex()is a single C-level builtin vs. multiple string operations for format string constructionzfill()directly pads with zeros instead of creating a format template.encode()step which creates an unnecessary bytes objectPerformance Impact:
The line profiler shows the optimized hex string creation (
hex_str = hex(num)[2:].zfill(2 * l)) takes 1.42ms vs. 1.57ms for the originalbinascii.unhexlify((fmt_str % num).encode())line - a ~10% improvement on the critical path.Test Case Benefits:
The optimization shows consistent 15-30% improvements across all test scenarios, with particularly strong gains for:
This optimization is especially valuable for cryptographic operations where
number_to_stringmay be called frequently during key generation or signature operations.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-SigningKey.to_string-mhy6keepand push.