⚡️ Speed up function deselect_by_keyword by 12%
#89
+19
−12
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.
📄 12% (0.12x) speedup for
deselect_by_keywordinsrc/_pytest/mark/__init__.py⏱️ Runtime :
30.0 milliseconds→26.7 milliseconds(best of129runs)📝 Explanation and details
The optimization achieves a 12% speedup by eliminating repeated attribute lookups and reducing function call overhead in hot paths. Here are the key improvements:
In
KeywordMatcher.from_item(the main bottleneck):Session = pytest.SessionandDirectory = pytest.Directoryoutside the loop eliminates repeatedpytest.attribute lookupsisinstance(node, pytest.Session)withtype(node) is Session, which is faster for exact type matchingIn
deselect_by_keyword:remaining.appendanddeselected.appendas local variables to avoid repeated attribute lookups in the tight loop over itemsWhy this matters for pytest workloads:
From the function references, this code is called in
pytest_collection_modifyitems, which processes every test item during collection. The performance gains scale linearly with test suite size - the larger test suites show 12-13% improvements in the annotated tests.Best performance gains observed in:
The optimizations are particularly effective because
KeywordMatcher.from_itemis called once per test item, making even small per-call improvements compound significantly across large test suites.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-deselect_by_keyword-mi9wz167and push.