⚡️ Speed up function is_file_content by 18%
#26
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.
📄 18% (0.18x) speedup for
is_file_contentinsrc/anthropic/_files.py⏱️ Runtime :
2.67 milliseconds→2.26 milliseconds(best of135runs)📝 Explanation and details
The optimization replaces multiple individual
isinstance()calls with a singleisinstance()call using a tuple of types. The key changes are:_FILE_CONTENT_TYPES = (bytes, tuple, io.IOBase, os.PathLike)is defined once at module levelisinstance(obj, _FILE_CONTENT_TYPES)instead of four separate calls connected byorWhy this is faster:
isinstance()function is optimized to handle tuple arguments efficiently in C code, avoiding the overhead of multiple function calls and boolean operationsisinstance()calls and 3orevaluations, while the optimized version makes just 1 function callorchain still requires multiple Python bytecode operations, whereas the tuple approach delegates the type checking to optimized C codePerformance characteristics from tests:
The 17% overall speedup comes from eliminating the Python-level boolean operations and multiple function call overhead in favor of a single optimized C-level type check.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_6zuacb2h/tmpwomw08wl/test_concolic_coverage.py::test_is_file_contentTo edit these changes
git checkout codeflash/optimize-is_file_content-mhe23dg7and push.