Latest Results
Optimize StructuredFormatter._format_exception
The optimized code achieves a **22% runtime improvement** (859μs → 702μs) through two key optimizations:
## Primary Optimizations
**1. Reduced Attribute Access Overhead in Traceback Loop**
The original code repeatedly accessed `tb.tb_frame.f_code` for each frame attribute (filename, function name). The optimization caches this in `f_code = tb.tb_frame.f_code` and `lineno = tb.tb_lineno`, eliminating redundant attribute traversals. While `linecache.getline()` still dominates at ~29% of runtime, reducing the surrounding attribute access overhead provides measurable gains.
**2. EAFP Pattern for Exception Chaining**
Replaced `hasattr()` checks with try/except blocks when accessing `__cause__` and `__context__`. In Python, try/except is faster than `hasattr()` when attributes typically exist (which is true for exception objects). The original code performed:
- `hasattr(exc_value, "__cause__")`
- `exc_value.__cause__` (if check passed)
- Similar for `__context__`
The optimized version directly accesses `exc_value.__cause__` once and handles the rare `AttributeError` case, reducing both function calls and attribute lookups.
## Performance Profile
The annotated tests show the optimization excels with **exceptions that have tracebacks** (6.56% faster for the traceback test case), where the frame processing loop benefits most from cached attribute access. For the no-exception case, there's a negligible regression (24.7% slower, but only ~41ns in absolute terms), which is an acceptable trade-off given the 22% overall speedup on realistic exception formatting workloads.
This optimization is particularly valuable when logging exceptions in error handling paths, where reducing the overhead of exception formatting directly improves application responsiveness during error conditions.codeflash/optimize-StructuredFormatter._format_exception-mlr42iaq Latest Branches
0%
codeflash/optimize-StructuredFormatter._format_exception-mlr42iaq 0%
codeflash/optimize-to_jsonschema_type-mlr7ormd 0%
feat/streams-from-catalog-2 © 2026 CodSpeed Technology