Skip to content

Commit 1786e34

Browse files
[perf] Skip the newline count on chunks without a newline
In ``pformat_lines``'s budget loop, ``chunk.count("\n")`` ran on every chunk, but most chunks (brackets, indentation, item reprs) contain no newline. Guarding the call with ``"\n" in chunk`` skips it on those and recovers part of the per-chunk budget-tracking overhead: formatting an 8-element list under a budget drops from ~0.0185 ms to ~0.0163 ms (versus ~0.0132 ms for an uncapped ``pformat().splitlines()``, so the budget overhead roughly halves, from ~+5 us to ~+3 us). The win is small and only matters on the ``-v`` truncating path of a failing assertion (the default path doesn't format the diff at all), so this is kept as a separate commit — easy to drop if the extra branch isn't judged worth it. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 4c3e153 commit 1786e34

1 file changed

Lines changed: 4 additions & 1 deletion

File tree

src/_pytest/_io/pprint.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,10 @@ def pformat_lines(
124124
chunks.append(chunk)
125125
if max_chars is not None:
126126
n_chars += len(chunk)
127-
if max_lines is not None:
127+
if max_lines is not None and "\n" in chunk:
128+
# Guard the count: most chunks (brackets, indents, item
129+
# reprs) have no newline, and skipping the call on them
130+
# is meaningfully cheaper than counting every chunk.
128131
n_lines += chunk.count("\n")
129132
if (max_lines is not None and n_lines >= max_lines) or (
130133
max_chars is not None and n_chars >= max_chars

0 commit comments

Comments
 (0)