⚡️ Speed up function load_image_base64 by 59%
#646
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.
📄 59% (0.59x) speedup for
load_image_base64ininference/core/utils/image_utils.py⏱️ Runtime :
18.1 milliseconds→11.4 milliseconds(best of42runs)📝 Explanation and details
The optimized code achieves a 58% speedup through three key optimizations:
1. Conditional regex processing: Instead of always running
BASE64_DATA_TYPE_PATTERN.sub()on every input string, the code first checks if the pattern matches usingBASE64_DATA_TYPE_PATTERN.match(). If a match is found, it uses string slicing to remove the prefix. This avoids expensive regex substitution for the majority of base64 strings that don't have data URI headers.2. Direct function call: Eliminates the intermediate
image_npvariable by passingnp.frombuffer()directly tocv2.imdecode(), reducing memory allocation overhead.3. Optimized empty check: Replaces
len(value) == 0withif not value:, which is more efficient in Python as it doesn't need to compute the length.The test results show this optimization is particularly effective for:
The optimizations maintain identical functionality and error handling while providing consistent performance improvements across all test cases.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
inference/unit_tests/core/utils/test_image_utils.py::test_load_image_base64_when_invalid_bytes_giveninference/unit_tests/core/utils/test_image_utils.py::test_load_image_base64_when_valid_bytes_giveninference/unit_tests/core/utils/test_image_utils.py::test_load_image_base64_when_valid_bytes_given_with_type_preambleinference/unit_tests/core/utils/test_image_utils.py::test_load_image_base64_when_valid_string_given🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-load_image_base64-mhcc32rmand push.