⚡️ Speed up function is_tokens_or_list_of_tokens by 121%
          #158
        
          
      
  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.
  
    
  
    
📄 121% (1.21x) speedup for
is_tokens_or_list_of_tokensinlitellm/llms/openai/completion/utils.py⏱️ Runtime :
3.55 milliseconds→1.60 milliseconds(best of188runs)📝 Explanation and details
The optimized code achieves a 121% speedup by replacing expensive
all()calls with explicit for-loops that provide better early exit behavior.Key optimizations:
Eliminated
all()overhead: The original code usesall(isinstance(item, int) for item in value)andall(isinstance(item, list) and all(isinstance(i, int) for i in item) for item in value). Theseall()calls create generator expressions and incur Python function call overhead for each element check.Explicit loops with early exit: The optimized version uses manual for-loops with
breakstatements that immediately exit when a non-matching type is found. This avoids the generator creation overhead and provides more efficient short-circuiting.Better loop control flow: Uses Python's
for-elseconstruct where theelseclause executes only if the loop completes without hitting abreak, providing cleaner early-exit logic.Performance gains by test case type:
The optimization is particularly effective for cases where invalid elements appear early in the list, as the manual loops can exit immediately rather than continuing to process remaining elements through the
all()generator pipeline.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_kt42dg31/tmpv2flhdwh/test_concolic_coverage.py::test_is_tokens_or_list_of_tokenscodeflash_concolic_kt42dg31/tmpv2flhdwh/test_concolic_coverage.py::test_is_tokens_or_list_of_tokens_2codeflash_concolic_kt42dg31/tmpv2flhdwh/test_concolic_coverage.py::test_is_tokens_or_list_of_tokens_3To edit these changes
git checkout codeflash/optimize-is_tokens_or_list_of_tokens-mhddzgjuand push.