⚡️ Speed up function list_trim by 5%
#117
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.
📄 5% (0.05x) speedup for
list_triminaerospike_helpers/operations/list_operations.py⏱️ Runtime :
238 microseconds→226 microseconds(best of5runs)📝 Explanation and details
The optimized code achieves a 5% runtime improvement (238μs → 226μs) by eliminating unnecessary dictionary mutation and reducing object operations.
Key optimization:
The original code always creates a base dictionary with 4 keys, then conditionally adds a 5th key (
CTX_KEY) via mutation. The optimized version constructs the complete dictionary in a single operation based on thectxtruthiness check, avoiding the mutation step entirely.Why this is faster:
dict_create → dict_assign → return, we now have justreturn dict_literal. Python's dictionary literal syntax{...}is highly optimized at the bytecode level.ctxkey, reducing memory allocations and potential cache misses.Performance characteristics from test results:
ctx=Noneor falsy values show the strongest improvement because they skip dictionary mutation entirelyctxvalues still benefit from single-pass dictionary creationMinor change: Import statements were reordered (PEP 8 style: standard library before third-party), which has no runtime impact.
This optimization is particularly valuable if
list_trimis called frequently in hot paths, as the per-call savings compound across many invocations.✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
test_nested_cdt_ctx.py::TestCTXOperations.test_ctx_list_trimtest_nested_cdt_ctx.py::TestCTXOperations.test_ctx_list_trim_negativetest_operate_helpers.py::TestOperate.test_pos_operate_with_list_trim_val_with_negative_value🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-list_trim-ml0n7ileand push.