⚡️ Speed up function extract_image_payload_and_type by 502%
#645
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.
📄 502% (5.02x) speedup for
extract_image_payload_and_typeininference/core/utils/image_utils.py⏱️ Runtime :
797 microseconds→132 microseconds(best of34runs)📝 Explanation and details
The optimized code achieves a 502% speedup through three key performance improvements:
1. Direct type comparison instead of
issubclass():issubclass(type(value), InferenceRequestImage)totype(value) is InferenceRequestImagetype(value) is dictinstead ofissubclass(type(value), dict)issubclass()performs expensive Method Resolution Order (MRO) traversal, whileisdoes a simple identity check2. Eliminated set construction on every call:
{e.value for e in ImageType}creates a new set each timeImageType._value2member_map_which is a pre-built dictionary mapping string values to enum members3. Reduced string operations:
image_type.lower()only once and stores the resultImageTypemember instead of constructing it withImageType(image_type.lower())The test results show consistent 4-8x speedups across all scenarios, with particularly strong performance on:
These optimizations maintain identical behavior and thread safety while eliminating redundant work on each function call.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
inference/unit_tests/core/utils/test_image_utils.py::test_extract_image_payload_and_type_when_type_cannot_be_inferredinference/unit_tests/core/utils/test_image_utils.py::test_extract_image_payload_and_type_when_value_is_dict_and_type_is_not_recognisedinference/unit_tests/core/utils/test_image_utils.py::test_extract_image_payload_and_type_when_value_is_dict_and_type_is_recognisedinference/unit_tests/core/utils/test_image_utils.py::test_extract_image_payload_and_type_when_value_is_request_and_type_is_not_recognisedinference/unit_tests/core/utils/test_image_utils.py::test_extract_image_payload_and_type_when_value_is_request_and_type_is_recognised🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-extract_image_payload_and_type-mhcbfac3and push.