⚡️ Speed up function api_error_handler by 36%
#20
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.
📄 36% (0.36x) speedup for
api_error_handlerinmem0/client/utils.py⏱️ Runtime :
402 microseconds→297 microseconds(best of25runs)📝 Explanation and details
The optimized version achieves a 35% speedup by moving the
functools.wrapsimport to module level instead of importing it inside the decorator function each time.Key Optimization:
from functools import wrapsstatement was moved from inside theapi_error_handlerfunction to the top-level imports. This eliminates the repeated import cost every time the decorator is instantiated.Why this matters:
In Python, imports have overhead even when the module is already cached. The original code performed this import operation every time
api_error_handlerwas called to decorate a function. With the optimization, the import happens only once when the module is loaded.Performance Impact:
Minor Change:
The optimized version also caches
str(e)asorig_errvariable in the exception handling block, avoiding multiple string conversions of the same exception object.Real-world benefit:
Since this is an error handling decorator likely used across multiple API client functions, the import cost savings accumulate significantly during application initialization when many decorated functions are defined. The 35% speedup in decorator creation directly translates to faster module loading and application startup times.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
⏪ Replay Tests and Runtime
test_pytest_testsconfigstest_prompts_py_testsvector_storestest_weaviate_py_testsllmstest_deepseek_py_test__replay_test_0.py::test_mem0_client_utils_api_error_handlertest_pytest_testsvector_storestest_opensearch_py_testsvector_storestest_upstash_vector_py_testsllmstest_l__replay_test_0.py::test_mem0_client_utils_api_error_handlerTo edit these changes
git checkout codeflash/optimize-api_error_handler-mhlij5ohand push.