Skip to content

gh-153568: Skip newline translation for source without carriage returns - #153584

Merged
pablogsal merged 1 commit into
python:mainfrom
pablogsal:gh-153568-newlines
Sep 14, 2026
Merged

pablogsal merged 1 commit into
python:mainfrom
pablogsal:gh-153568-newlines

Conversation

@pablogsal

@pablogsal pablogsal commented Jul 11, 2026 •

Copy link
Copy Markdown
Member

The tokenizer normalizes newlines by copying the whole input one byte at a time through a state machine, but virtually all source today has no carriage returns at all, in which case the translation is the identity. A single memchr decides that up front and replaces the byte loop with one memcpy; inputs containing carriage returns keep the existing path, including lone-CR and CRLF handling.

Benchmark (parsing 8 of the largest stdlib files, 1.3 MB, 20 times per run with _PyParser_ASTFromString — parser only, no AST-to-Python conversion; turbo disabled, performance governor, FIFO-pinned to a dedicated core, interleaved runs):

build time per run executed instructions
main 143.8 ms 23.16G
this PR 142.5 ms 22.74G (1.8% fewer)

About a 1% wall-clock win: small, but stable across runs and the diff is eight lines.

Comment thread Parser/tokenizer/helpers.c Outdated
Comment on lines +282 to +283
c = input_length ? s[input_length - 1] : '\0';
goto add_final_newline;

@maurycy maurycy Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
c = input_length ? s[input_length - 1] : '\0';
goto add_final_newline;
if (exec_input && input_length && s[input_length - 1] != '\n') {
*current++ = '\n';
}
*current = '\0';
return buf;

Do you think it makes sense to spare a PyMem_Realloc()?

… returns

The tokenizer copied every input byte by byte to normalize newlines,
but source without a carriage return needs no translation and can be
copied verbatim.
@pablogsal
pablogsal enabled auto-merge (squash) September 14, 2026 15:41
@pablogsal
pablogsal merged commit 0d6671d into python:main Sep 14, 2026
53 of 54 checks passed
@pablogsal
pablogsal deleted the gh-153568-newlines branch September 14, 2026 16:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants