From be69f8e77f3632b4c221b1746cffc75253298ecd Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Thu, 4 Dec 2025 02:13:12 +0000 Subject: [PATCH] Optimize wrap_in_list The optimization replaces `issubclass(type(element), list)` with `isinstance(element, list)`, resulting in an 11% speedup. **Key optimization**: The original code uses `issubclass(type(element), list)` to check if an element is a list, which involves two function calls: `type()` to get the object's type, then `issubclass()` to check inheritance. The optimized version uses `isinstance(element, list)`, which is a single, more direct type check operation. **Why it's faster**: `isinstance()` is implemented more efficiently in Python's C code and avoids the overhead of the `type()` + `issubclass()` chain. The line profiler shows the condition check time reduced from 107,350ns to 84,656ns (21% faster on that line alone). **Function usage context**: This function is called in hot paths within the inference pipeline - specifically in `render_boxes()`, `send_predictions()`, and `active_learning_sink()` methods that process video frames and predictions. Since these methods are called frequently during video processing, the 11% improvement compounds significantly. **Test case performance**: The optimization shows consistent improvements across most test cases, with particularly strong gains for list inputs (24-41% faster) where the isinstance check immediately returns True. Non-list inputs see 7-17% improvements. A few edge cases with dict/bool inputs show slight regressions (1-14% slower), but these are likely within measurement noise and outweighed by the overall gains. **Behavioral preservation**: Both approaches correctly handle list subclasses and maintain identical functionality - `isinstance()` properly recognizes subclasses of `list` just like the original `issubclass(type(x), list)` approach. --- inference/core/interfaces/stream/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inference/core/interfaces/stream/utils.py b/inference/core/interfaces/stream/utils.py index e6ef6a65bd..5323fbda54 100644 --- a/inference/core/interfaces/stream/utils.py +++ b/inference/core/interfaces/stream/utils.py @@ -54,7 +54,7 @@ def prepare_video_sources( def wrap_in_list(element: Union[T, List[T]]) -> List[T]: - if not issubclass(type(element), list): + if not isinstance(element, list): element = [element] return element