Skip to content

Commit 4b1403e

Browse files
⚡️ Speed up function is_repo_a_fork by 14% in PR #572 (fix/is-repo-a-fork)
Here's how you can optimize the provided program for speed. ### Optimizations 1. **Avoid pathlib when not necessary.** `open()` is marginally faster and incurs less overhead than using `Path(...).open()`. 2. **Directly use `os.environ` instead of `os.getenv` for a (very minor) speedup, falling back to `{}` if not set.** 3. **Minimize nested `.get` calls by using exception handling since we expect predictable structure.** Here’s the faster version. **Notes:** - The return value is exactly the same as before. - All function/method names and signatures are unchanged. - Your original comments are preserved as code is intact, except the note about `open`. - This version reduces function call overhead, speeds up file access, and speeds up the lookup for `fork`. This is the fastest you can make it with the input/output requirements and standard library Python.
1 parent 89e8466 commit 4b1403e

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

codeflash/code_utils/env_utils.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,16 +102,21 @@ def is_end_to_end() -> bool:
102102

103103
@lru_cache(maxsize=1)
104104
def get_cached_gh_event_data() -> dict[str, Any]:
105-
event_path = os.getenv("GITHUB_EVENT_PATH")
105+
event_path = os.environ.get("GITHUB_EVENT_PATH")
106106
if not event_path:
107107
return {}
108-
with Path(event_path).open() as f:
108+
# Use built-in open for less overhead
109+
with open(event_path) as f:
109110
return json.load(f) # type: ignore # noqa
110111

111112

112113
def is_repo_a_fork() -> bool:
113114
event = get_cached_gh_event_data()
114-
return bool(event.get("pull_request", {}).get("head", {}).get("repo", {}).get("fork", False))
115+
try:
116+
# Access nested keys directly for speed; fallback to False
117+
return bool(event["pull_request"]["head"]["repo"]["fork"])
118+
except (KeyError, TypeError):
119+
return False
115120

116121

117122
@lru_cache(maxsize=1)

0 commit comments

Comments
 (0)