From 31923adc680df0fcb2fce07cdc955c5eb135f317 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Fri, 7 Nov 2025 15:41:31 +0000 Subject: [PATCH] Optimize to_hexstr The optimization leverages Python's built-in `bytes.hex()` method for the common case where the input is a `bytes` object, providing a **27% speedup**. **Key Changes:** - Added a type check `isinstance(s, bytes)` to identify when the input is a `bytes` object - For `bytes` inputs, use the native `.hex()` method instead of `binascii.hexlify(s).decode('ascii')` - Fallback to the original `binascii.hexlify()` approach for other types like `bytearray` **Why It's Faster:** The `bytes.hex()` method is implemented in C and optimized specifically for converting bytes to hexadecimal strings, avoiding the overhead of: 1. Calling the `binascii.hexlify()` function 2. The additional `.decode('ascii')` step to convert bytes to string **Performance Impact:** - **Bytes inputs (80% of test cases)**: 28-69% faster, with most cases showing 40-60% improvement - **Non-bytes inputs (bytearray, invalid types)**: 7-30% slower due to the added type check overhead - **Large data (1KB)**: 24-52% faster, showing the optimization scales well The performance profile shows that 80% of calls (40 out of 50) take the fast path through `s.hex()`, making this optimization highly effective for the typical use case of converting `bytes` objects to hex strings in cryptocurrency/hardware wallet operations. --- electrum/plugins/digitalbitbox/digitalbitbox.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/electrum/plugins/digitalbitbox/digitalbitbox.py b/electrum/plugins/digitalbitbox/digitalbitbox.py index 00b90309ba59..401e10338807 100644 --- a/electrum/plugins/digitalbitbox/digitalbitbox.py +++ b/electrum/plugins/digitalbitbox/digitalbitbox.py @@ -60,6 +60,8 @@ class DeviceErased(UserFacingException): def to_hexstr(s): + if isinstance(s, bytes): + return s.hex() return binascii.hexlify(s).decode('ascii')