⚡️ Speed up function under_non_alpha_ratio by 76%
          #4079
        
          
      
                
     Merged
            
            
          
  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.
  
    
  
    
📄 76% (0.76x) speedup for
under_non_alpha_ratioinunstructured/partition/text_type.py⏱️ Runtime :
9.53 milliseconds→5.41 milliseconds(best of91runs)📝 Explanation and details
Here's an optimized version of your function.
Major improvements.
char.strip()is only used to check for non-space; you can check explicitly for that.Here's the optimized code with all original comments retained.
This approach processes the string only once and uses O(1) memory (just two ints). The use of
char.isspace()is a fast way to check for all Unicode whitespace, just as before. This will significantly speed up your function and eliminate almost all time spent in the original two list comprehensions.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
partition/test_text_type.py::test_under_non_alpha_ratio_zero_dividetest_tracer_py__replay_test_0.py::test_unstructured_partition_text_type_under_non_alpha_ratiotest_tracer_py__replay_test_2.py::test_unstructured_partition_text_type_under_non_alpha_ratiotest_tracer_py__replay_test_3.py::test_unstructured_partition_text_type_under_non_alpha_ratio🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-under_non_alpha_ratio-mcgm6dorand push.