⚡️ Speed up method RC.exists
by 289%
#50
Open
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.
📄 289% (2.89x) speedup for
RC.exists
inguardrails/classes/rc.py
⏱️ Runtime :
4.85 milliseconds
→1.25 milliseconds
(best of81
runs)📝 Explanation and details
The optimization introduces path caching to eliminate redundant filesystem path computations on repeated calls to
RC.exists()
.Key optimization:
.guardrailsrc
file path as a static attribute (_guardrails_rc
) on the method itselfexpanduser("~")
andos.path.join()
once on the first call, then reuses the cached pathWhy this creates a speedup:
The line profiler shows that
expanduser("~")
was the most expensive operation (61.6% of runtime, 6638ns per hit). This function performs system calls to resolve the home directory, which is computationally expensive but always returns the same value during program execution. By eliminating 2023 out of 2024 calls toexpanduser()
and the correspondingos.path.join()
operations, the optimization reduces the total function time from 21.8ms to 4.4ms.Test case performance patterns:
The optimization is particularly effective for applications that check the
.guardrailsrc
file existence multiple times, as the expensive path resolution only happens once.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-RC.exists-mh1ldavh
and push.