Skip to content

Commit

Permalink
⚡️ Speed up method StreamAvailabilityStrategy.check_availability by…
Browse files Browse the repository at this point in the history
… 10% in PR #45673 (`async-job-salesforce/cdk-release`)

Certainly! To make this Python program faster, I'll focus on some areas for optimization. Since Python is an interpreted language, some practices favor readability over performance, but there are still ways to optimize such as.

1. **Remove Redundant Checks**: In the `StreamAvailabilityStrategy` class, there’s a check for the availability of the `check_availability` method, which could be moved out of the try-except block to lower the overhead.
2. **Avoid Repeated Attribute Lookups**: Cache attribute lookups to improve runtime.

Here's the optimized code.


### Changes Made.
1. **Moved the check for `check_availability` out of the `try` block**: It reduces the overhead of entering and exiting the `try` block unnecessarily.
2. **Used `getattr` with default value**: This way, the check if `stream_check_avail` is `None` makes the code more readable and Pythonic.

These small but potent changes can improve the runtime efficiency and readability of your code. They help in minimizing redundant operations and improve overall performance.
  • Loading branch information
codeflash-ai[bot] committed Sep 19, 2024
1 parent e5cae76 commit 2de7da0
Showing 1 changed file with 13 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -375,19 +375,20 @@ def __init__(self, stream: Stream, source: Source):
self._source = source

def check_availability(self, logger: logging.Logger) -> StreamAvailability:
try:
if hasattr(self._stream, "check_availability"):
available, message = self._stream.check_availability(logger, self._source)
stream_check_avail = getattr(self._stream, "check_availability", None)
if stream_check_avail is not None:
try:
available, message = stream_check_avail(logger, self._source)
if available:
return StreamAvailable()
else:
return StreamUnavailable(str(message))
else:
# Given no availability strategy, we will assume the stream is available
return StreamAvailable()
except Exception as e:
display_message = self._stream.get_error_display_message(e)
if display_message:
raise ExceptionWithDisplayMessage(display_message)
else:
raise e
except Exception as e:
display_message = self._stream.get_error_display_message(e)
if display_message:
raise ExceptionWithDisplayMessage(display_message)
else:
raise e
else:
# Given no availability strategy, we will assume the stream is available
return StreamAvailable()

0 comments on commit 2de7da0

Please sign in to comment.