Skip to content

Commit e8fba39

Browse files
⚡️ Speed up function get_cached_gh_event_data by 13% (#975)
* Optimize get_cached_gh_event_data The optimization replaces `Path(event_path).open(encoding="utf-8")` with the built-in `open(event_path, encoding="utf-8")`, achieving a **12% speedup** by eliminating unnecessary object allocation overhead. **Key optimization:** - **Removed Path object creation**: The original code creates a `pathlib.Path` object just to call `.open()` on it, when the built-in `open()` function can directly accept the string path from `event_path`. - **Reduced memory allocation**: Avoiding the intermediate `Path` object saves both allocation time and memory overhead. **Why this works:** In Python, `pathlib.Path().open()` internally calls the same file opening mechanism as the built-in `open()`, but with additional overhead from object instantiation and method dispatch. Since `event_path` is already a string from `os.getenv()`, passing it directly to `open()` is more efficient. **Performance impact:** The test results show consistent improvements across all file-reading scenarios: - Simple JSON files: 12-20% faster - Large files (1000+ elements): 3-27% faster - Error cases (missing files): Up to 71% faster - The cached calls remain unaffected (0% change as expected) **Workload benefits:** Based on the function references, `get_cached_gh_event_data()` is called by multiple GitHub-related utility functions (`get_pr_number()`, `is_repo_a_fork()`, `is_pr_draft()`). While the `@lru_cache(maxsize=1)` means the file is only read once per program execution, this optimization reduces the initial cold-start latency for GitHub Actions workflows or CI/CD pipelines where these functions are commonly used. The optimization is particularly effective for larger JSON files and error handling scenarios, making it valuable for robust CI/CD environments that may encounter various file conditions. * ignore --------- Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com> Co-authored-by: Kevin Turcios <[email protected]>
1 parent fe2a5a2 commit e8fba39

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

codeflash/code_utils/env_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def get_cached_gh_event_data() -> dict[str, Any]:
155155
event_path = os.getenv("GITHUB_EVENT_PATH")
156156
if not event_path:
157157
return {}
158-
with Path(event_path).open(encoding="utf-8") as f:
158+
with open(event_path, encoding="utf-8") as f: # noqa: PTH123
159159
return json.load(f) # type: ignore # noqa
160160

161161

0 commit comments

Comments
 (0)