⚡️ Speed up method SparseVectorIndexConfig.validate_embedding_function_field by 69%
#122
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.
📄 69% (0.69x) speedup for
SparseVectorIndexConfig.validate_embedding_function_fieldinchromadb/api/types.py⏱️ Runtime :
1.71 milliseconds→1.01 milliseconds(best of102runs)📝 Explanation and details
The optimization introduces signature caching to eliminate redundant computation during validation. The key changes are:
Cached protocol signature: The protocol signature
signature(SparseEmbeddingFunction.__call__).parameters.keys()is computed once and cached globally, rather than being recomputed on every validation call.Tuple conversion for faster comparison: Both signatures are converted to tuples instead of comparing
dict_keysobjects directly, which provides faster equality comparison in Python.Lazy initialization: The protocol signature is computed only when first needed via
_get_protocol_signature(), avoiding any import-time overhead.Why this leads to speedup: The
inspect.signature()function performs introspection on the method, which involves parsing the function's metadata. This is computationally expensive when done repeatedly. By caching the protocol signature (which never changes), we eliminate this repeated work. The tuple conversion also optimizes the comparison operation itself.Test case performance patterns: The optimization shows consistent 30-40% speedups across all test cases that involve signature validation (e.g.,
test_valid_sparse_embedding_function: 38.9% faster,test_multiple_instances_large_scale: 90.3% faster). The most dramatic improvements occur in scenarios with multiple validations, where the caching benefit compounds. Simple cases liketest_none_embedding_functionshow minimal impact since they bypass signature validation entirely.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-SparseVectorIndexConfig.validate_embedding_function_field-mh7dusnpand push.