⚡️ Speed up function _build_filters_and_metadata by 627%
#5
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.
📄 627% (6.27x) speedup for
_build_filters_and_metadatainmem0/memory/main.py⏱️ Runtime :
1.67 milliseconds→229 microseconds(best of33runs)📝 Explanation and details
The optimized code achieves a 626% speedup through two key changes that eliminate unnecessary overhead:
1. Replace
deepcopy()with shallowcopy()deepcopy()oninput_metadataandinput_filters, which recursively copies all nested objectscopy(), which only copies the top-level dictionary2. Replace list tracking with integer counter
session_ids_provided = []and callsappend()for each session IDsession_ids_provided = 0and increments with+= 1Performance benefits by test case type:
deepcopyoverhead scales with dict size whilecopy()remains constantThe optimizations are particularly effective when
input_metadataorinput_filterscontain large or nested dictionaries, which is common in production memory management scenarios.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
⏪ Replay Tests and Runtime
test_pytest_testsvector_storestest_opensearch_py_testsvector_storestest_upstash_vector_py_testsllmstest_l__replay_test_0.py::test_mem0_memory_main__build_filters_and_metadataTo edit these changes
git checkout codeflash/optimize-_build_filters_and_metadata-mhk06qj1and push.