⚡️ Speed up method UniversalBaseModel.construct by 8%
          #8
        
          
      
  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.
  
    
  
    
📄 8% (0.08x) speedup for
UniversalBaseModel.constructinsrc/deepgram/core/pydantic_utilities.py⏱️ Runtime :
128 milliseconds→119 milliseconds(best of32runs)📝 Explanation and details
The optimized code achieves a 7% speedup by introducing cached type introspection functions to eliminate redundant expensive calls to
typing_extensionsutilities.Key optimizations:
LRU-cached type introspection helpers: Added
@lru_cache(maxsize=128)decorators to_get_origin_cached(),_get_args_cached(), and_is_typeddict_cached()functions. This eliminates repeated expensive type analysis calls that were consuming significant time in the profiler.Local caching of origin lookups: Introduced
clean_type_origin = _get_origin_cached(clean_type)to avoid callingget_originmultiple times for the same type within a single function call.Tuple unpacking optimization: Changed
typing_extensions.get_args(clean_type)[0]patterns to tuple unpacking like(inner_container_type,) = _get_args_cached(clean_type)andkey_type, value_type = _get_args_cached(clean_type), reducing indexing overhead.Why it's faster: The line profiler shows that repeated calls to
typing_extensions.get_origin()were major bottlenecks (consuming 1.2-1.6% each). By caching these introspection results, the optimized version reduces the time spent on type analysis from ~39ms to ~35ms in the core function.Best performance gains are seen in test cases with:
The caching is particularly effective because the same types are often analyzed repeatedly during recursive traversal of nested data structures.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-UniversalBaseModel.construct-mh2t5zfkand push.