Skip to content

gh-156955: Speed up csv.writer by caching the set of special characters - #157298

Merged
serhiy-storchaka merged 4 commits into
python:mainfrom
serhiy-storchaka:csv-writer-special-bitmap
Sep 13, 2026
Merged

gh-156955: Speed up csv.writer by caching the set of special characters#157298
serhiy-storchaka merged 4 commits into
python:mainfrom
serhiy-storchaka:csv-writer-special-bitmap

Conversation

@serhiy-storchaka

Copy link
Copy Markdown
Member

Cache in the dialect a 128-bit set of ASCII characters that need quoting or escaping (delimiter, quotechar, escapechar, \r, \n and the characters of lineterminator), and a flag whether any of them is non-ASCII. Testing a character is now one bit test instead of five comparisons and a call to PyUnicode_FindChar(); the old chain is only used for non-ASCII characters when the dialect has a non-ASCII special character.

Alternative to #156956 (which only caches the maximum character of lineterminator). Results with the same interleaved benchmark (release build, non-PGO), median of 15 rounds:

case main #156956 this PR
text 2000x4 0.768 ms 2.48x 3.55x
wide 500x2 (200-char fields) 1.340 ms 2.88x 4.41x
non-ASCII 500x5 3.040 ms 2.26x 3.33x
quoted 2000x4 0.279 ms 1.43x 1.53x
short 5000x4 0.508 ms 1.41x 1.38x
int rows 2000x10 1.110 ms 1.18x 1.14x
lineterminator='\n' 0.714 ms 2.50x 3.69x
lineterminator='END' 0.788 ms 2.30x 3.96x

Fields of 2000 characters are written 4.6x faster, of 20000 characters 5.9x faster.

Tests now cover non-ASCII delimiter, quotechar, escapechar and lineterminator in the writer.

🤖 Generated with Claude Code

…aracters

Cache in the dialect a 128-bit set of ASCII characters which need quoting
or escaping (delimiter, quotechar, escapechar, '\r', '\n' and characters
of lineterminator) and a flag whether any of them is non-ASCII.
Testing a character is now one bit test instead of five comparisons and
a call to PyUnicode_FindChar().

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

@eendebakpt eendebakpt left a comment

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.

Nice! A tiny suggestion to reduce the amount of comments (can be used as other places as well), but it is a matter of tase.

Comment thread Modules/_csv.c Outdated
@serhiy-storchaka
serhiy-storchaka enabled auto-merge (squash) September 13, 2026 08:00
@serhiy-storchaka
serhiy-storchaka merged commit a60343e into python:main Sep 13, 2026
99 of 102 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants