Skip to content

perf: use memoryview in write() to avoid copies#954

Merged
Kludex merged 3 commits into
pydantic:mainfrom
mbeijen:perf/memoryview-write
May 20, 2026
Merged

perf: use memoryview in write() to avoid copies#954
Kludex merged 3 commits into
pydantic:mainfrom
mbeijen:perf/memoryview-write

Conversation

@mbeijen
Copy link
Copy Markdown
Contributor

@mbeijen mbeijen commented May 17, 2026

Summary

Use memoryview slicing in TLSinTLSStream.write() and SyncStream.write() so that each iteration of the send loop does a zero-copy view advance instead of copying the remaining buffer bytes. Most visible on large POST uploads where partial sends cause repeated re-copies of the tail.

Ported from https://codeberg.org/httpxyz/httpcorexyz/pulls/4

Closes #912
Closes encode/httpcore#1029

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 17, 2026

Merging this PR will improve performance by ×410

⚡ 1 improved benchmark
✅ 6 untouched benchmarks

Performance Changes

Mode Benchmark BASE HEAD Efficiency
WallTime test_bench_sync_stream_write_large 113,272.5 ms 278.5 ms ×410

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing mbeijen:perf/memoryview-write (d9f6930) with main (ca874b3)

Open in CodSpeed

@Kludex
Copy link
Copy Markdown
Member

Kludex commented May 17, 2026

I'm experimenting some benchmark strategies. Sorry the noise.

Use memoryview slicing in TLSinTLSStream.write() and SyncStream.write()
so that each iteration of the send loop does a zero-copy view advance
instead of copying the remaining buffer bytes. Most visible on large
POST uploads where partial sends cause repeated re-copies of the tail.

Ported from https://codeberg.org/httpxyz/httpcorexyz/pulls/4

Closes pydantic#912
Closes encode/httpcore#1029

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: naarob <laforge@forge-sync.local>
Kludex added 2 commits May 20, 2026 08:54
The test only verifies correctness on a normal socket and does not
regression-test the perf fix (it passes equally well against the old
bytes-slicing code).
@Kludex
Copy link
Copy Markdown
Member

Kludex commented May 20, 2026

I've run some tests locally, and I see this dramatically increases the performance.

The benchmark setup needs improvements tho. 😞


I'm dropping the test. I prefer to have regression tests focused on high level API.

@Kludex Kludex merged commit 79f788b into pydantic:main May 20, 2026
9 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

2 participants