Skip to content

Commit

Permalink
⚡️ Speed up method DuckDuckGoSearchComponent._build_wrapper by 1,59…
Browse files Browse the repository at this point in the history
…8% in PR #6028 (`PlaygroundPage`)

To optimize the given Python program for faster runtime, consider the following changes.

1. **Avoid Redundant Instantiation**: Ensure that the `DuckDuckGoSearchRun` wrapper is instantiated only once and reused.
2. **Lazily Load Heavy Operations**: Only initialize and use the `DuckDuckGoSearchRun` object when needed.




### Explanation

1. **Initialization in Constructor**: We introduce a private variable `_ddg_search_wrapper` which will store the instance of the `DuckDuckGoSearchRun`.
2. **Lazy Initialization**: In the `_build_wrapper` method, we check if `_ddg_search_wrapper` is `None`. If it is, we instantiate `DuckDuckGoSearchRun`, ensuring that it only happens once, thus avoiding redundant instantiation.

These changes ensure that the wrapper is only instantiated once and reused, reducing the overhead and improving the performance of the component.
  • Loading branch information
codeflash-ai[bot] authored Feb 7, 2025
1 parent ef6af98 commit 44c4448
Showing 1 changed file with 9 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ class DuckDuckGoSearchComponent(Component):
]

def _build_wrapper(self) -> DuckDuckGoSearchRun:
"""Build the DuckDuckGo search wrapper."""
return DuckDuckGoSearchRun()
"""Build or return the DuckDuckGo search wrapper."""
if self._ddg_search_wrapper is None:
self._ddg_search_wrapper = DuckDuckGoSearchRun()
return self._ddg_search_wrapper

def run_model(self) -> list[Data]:
return self.fetch_content()
Expand Down Expand Up @@ -89,3 +91,8 @@ def fetch_content_text(self) -> Message:
result_string = "\n".join(item.text for item in data)
self.status = result_string
return Message(text=result_string)

def __init__(self):
"""Initialize the component and set up the wrapper."""
super().__init__()
self._ddg_search_wrapper = None

0 comments on commit 44c4448

Please sign in to comment.