⚡️ Speed up method SkyvernLogEncoder._format_value by 86%
#114
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.
📄 86% (0.86x) speedup for
SkyvernLogEncoder._format_valueinskyvern/forge/skyvern_log_encoder.py⏱️ Runtime :
176 microseconds→94.8 microseconds(best of93runs)📝 Explanation and details
The optimized code achieves an 85% speedup through two key optimizations that target different usage patterns:
1. LRU Caching for Immutable Values
The major optimization adds
@functools.lru_cache(maxsize=128)to cache JSON serialization results for hashable (immutable) values like strings, integers, booleans, tuples, and None. When_format_valueis called with the same immutable value repeatedly, it returns the cached result instead of re-serializing. The test results show dramatic speedups for primitive types (500-1000% faster) because these values are likely repeated frequently in logging scenarios.2. Kwargs Optimization in JSON Encoder
The
SkyvernJSONLogEncoder.dumpsmethod now directly inserts'cls'into the kwargs dictionary instead of passing it as a separate parameter tojson.dumps. This eliminates the overhead of Python's keyword argument handling when the method is called frequently.Performance Impact by Use Case:
Real-World Benefits:
Based on the function reference showing
_format_valueis called in a loop within_parse_json_entry, this optimization is particularly valuable for log processing where the same status codes, event types, or common values appear repeatedly across multiple log entries. The caching ensures these repeated values are serialized only once, dramatically reducing CPU overhead in log-heavy applications.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-SkyvernLogEncoder._format_value-mirdqew4and push.