⚡️ Speed up _one_of_ours()
by 7% in scanpy/_utils/__init__.py
#39
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.
📄
_one_of_ours()
inscanpy/_utils/__init__.py
📈 Performance improved by
7%
(0.07x
faster)⏱️ Runtime went down from
1.60μs
to1.50μs
Explanation and details
(click to show)
When optimizing a program for speed, you generally want to minimize expensive operations and remove any unnecessary ones. In this function, we can achieve this by using the walrus operator ':=' (assignment expression) introduced in Python 3.8 and rearranging the conditions for early returning when possible.
Also, accessing attributes of an object using dot notation is generally faster than using the getattr function. Here is a refactored function.
The advantage of using this technique is that the function will return as soon as it finds that one of the conditions is not met without needing to check all the conditions. Furthermore, it reduces the need to call functions (like getattr) multiple times, which helps in improving the function's speed.
Correctness verification
The new optimized code was tested for correctness. The results are listed below.
🔘 (none found) − ⚙️ Existing Unit Tests
✅ 1 Passed − 🌀 Generated Regression Tests
(click to show generated tests)