⚡️ Speed up function is_primitive by 13%
#462
Open
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.
📄 13% (0.13x) speedup for
is_primitiveinnvflare/tool/job/config/config_indexer.py⏱️ Runtime :
2.33 milliseconds→2.07 milliseconds(best of105runs)📝 Explanation and details
The optimization combines multiple
isinstance()calls into a single call using a tuple of types, reducing function call overhead and improving performance by ~12%.Key changes:
isinstance()calls chained withor, the code now usesisinstance(value, _PRIMITIVE_TYPES)where_PRIMITIVE_TYPES = (int, float, str, bool)is a pre-allocated tuple constant.isinstance()calls per invocation, while the optimized version makes only 1 call for primitive types.Why this is faster:
isinstance()with a tuple of types is optimized in CPython to check all types in a single C-level loop, avoiding Python function call overhead between checks_PRIMITIVE_TYPESis allocated once at module load time rather than being recreated implicitly in each callPerformance characteristics:
The optimization is particularly effective because
isinstance()with multiple types is a well-optimized CPython operation, making this a classic Python performance pattern.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-is_primitive-mhe3f9h1and push.