⚡️ Speed up function deselect_by_mark by 5%
#90
+11
−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.
📄 5% (0.05x) speedup for
deselect_by_markinsrc/_pytest/mark/__init__.py⏱️ Runtime :
8.22 milliseconds→7.81 milliseconds(best of147runs)📝 Explanation and details
The optimization achieves a 5% speedup through two key micro-optimizations that reduce overhead in tight loops:
What optimizations were applied:
Method lookup caching in
deselect_by_mark: Extractedremaining.appendanddeselected.appendto local variables before the main loop, avoiding repeated attribute lookups on each iteration.Constant hoisting in
Expression.evaluate: Moved the empty{"__builtins__": {}}dictionary to a module-level constant_EMPTY_BUILTINS, eliminating dictionary creation on every evaluation.Why these optimizations work:
Attribute lookup reduction: Python's attribute access (
obj.method) involves dictionary lookups that are slower than local variable access. In the main loop that processes thousands of items, this overhead accumulates significantly.Object allocation elimination: Creating the builtins dictionary on every
eval()call adds memory allocation overhead. Since the dictionary is always identical and immutable, reusing a constant is more efficient.Performance impact based on test results:
The optimization shows strongest gains on large-scale workloads (6-8% faster on tests with 1000 items) where the loop overhead dominates. Small test cases show minimal or slightly negative impact due to the added variable assignments, but these are negligible in real-world usage.
Context significance:
Given that
deselect_by_markis called frompytest_collection_modifyitemsduring test collection, this optimization directly benefits pytest's test discovery phase. Since test collection happens before every test run and can involve hundreds or thousands of test items, even small per-item optimizations provide meaningful cumulative speedups for developer workflow.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-deselect_by_mark-mi9x51dgand push.