Skip to content

gh-162513: Use memcmp() for equality comparisons between contiguous byte memoryviews - #162514

Open
maurycy wants to merge 6 commits into
python:mainfrom
maurycy:memoryview-byte-equality
Open

maurycy wants to merge 6 commits into
python:mainfrom
maurycy:memoryview-byte-equality

Conversation

@maurycy

@maurycy maurycy commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Compare a run of bytes in one call to memcmp() in cmp_base(). The fast path applies when both operands have the same native format (B, b or c), both strides are one byte, both suboffset arrays are null, and the run is not empty.

This covers a B view compared with bytes or bytearray, and contiguous rows of multidimensional views.

Comparisons between different formats still use struct unpacking.

Closes #162513

macOS PGO+LTO:

Comparison main Patch main / patch
4 KiB, equal 8.43 µs 95.0 ns 88.73×
4 KiB, last byte differs 8.45 µs 95.9 ns 88.13×
4 KiB, first byte differs 15.2 ns 14.9 ns 1.02×
8 bytes, equal 22.2 ns 15.0 ns 1.48×
Every other byte, 2,048 elements 4.2 µs 4.17 µs 1.01×
Equal 32 × 64 views, contiguous rows, outer stride 128 4.21 µs 164.4 ns 25.58×
Open, map and compare two copies of the pip wheel 5.81 ms 314 µs 18.54×
Expression Size Equal, main Equal, patch First byte differs, main First byte differs, patch
mv == value 0 B 14.8 ns 15.6 ns — —
mv == value 1 B 16.6 ns 17.2 ns 16.2 ns 17.3 ns
mv == value 4 B 19.9 ns 16.7 ns 16.6 ns 17.0 ns
mv == value 16 B 35.8 ns 16.6 ns 16.8 ns 17.0 ns
mv == value 100 B 207.9 ns 18.0 ns 17.0 ns 16.7 ns
packet[:4] == magic 4 B 42.8 ns 37.6 ns 38.9 ns 38.7 ns
packet[:16] == magic 16 B 57.6 ns 38.9 ns 38.8 ns 38.6 ns
Comparison main Patch main / patch
Unsigned byte view vs. bytearray, 100 bytes, equal 205.7 ns 18.5 ns 11.15×
Signed byte view (b) vs. bytes, 4 zero bytes, equal 744.9 ns 758.2 ns 0.98×
Character view (c) vs. bytes, 4 zero bytes, unequal 609.5 ns 615.6 ns 0.99×
bench
import ensurepip
import mmap
import tempfile
from pathlib import Path

import pyperf


def compare_files(path1, path2):
    with path1.open("rb") as f1, path2.open("rb") as f2:
        with (
            mmap.mmap(f1.fileno(), 0, access=mmap.ACCESS_READ) as m1,
            mmap.mmap(f2.fileno(), 0, access=mmap.ACCESS_READ) as m2,
            memoryview(m1) as v1,
            memoryview(m2) as v2,
        ):
            return v1 == v2


left = memoryview(bytearray(4096))
right = memoryview(bytearray(4096))
first_diff = memoryview(b"x" + bytes(4095))
last_diff = memoryview(bytes(4095) + b"x")
short_left, short_right = left[:8], right[:8]
strided_left, strided_right = left[::2], right[::2]

runner = pyperf.Runner()
for stmt in (
    "left == right",
    "left == last_diff",
    "left == first_diff",
    "short_left == short_right",
    "strided_left == strided_right",
):
    runner.timeit(stmt, stmt, globals=globals())

packet = memoryview(bytes(128))
for size in (0, 1, 4, 16, 100):
    view = packet[:size]
    equal = bytes(size)
    runner.timeit(f"mv == bytes/{size}/equal", "view == equal", globals=globals())
    if size:
        miss = b"x" + bytes(size - 1)
        runner.timeit(f"mv == bytes/{size}/first differs", "view == miss", globals=globals())
    if size in (4, 16):
        for outcome, magic in (("equal", equal), ("first differs", miss)):
            stmt = f"packet[:{size}] == magic"
            runner.timeit(f"slice == bytes/{size}/{outcome}", stmt, globals=globals())

mutable = bytearray(100)
view = packet[:100]
signed = packet[:4].cast("b")
chars = packet[:4].cast("c")
raw = bytes(4)
rows_left = left.cast("B", (64, 64))[::2]
rows_right = right.cast("B", (64, 64))[::2]
for stmt in ("view == mutable", "signed == raw", "chars == raw", "rows_left == rows_right"):
    runner.timeit(stmt, stmt, globals=globals())

wheel = next(Path(ensurepip.__file__).with_name("_bundled").glob("pip-*.whl"))
with tempfile.TemporaryDirectory() as tmp:
    copy = Path(tmp) / wheel.name
    copy.write_bytes(wheel.read_bytes())
    assert compare_files(wheel, copy)
    runner.bench_func("open, mmap and compare two pip wheels", compare_files, wheel, copy)

@maurycy

maurycy commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

cc @cmaloney :)

@cmaloney

Copy link
Copy Markdown
Contributor

This is a subset of what I was doing in #159716 (comment) which mainly just needs reviews.

That generalized so anything that can export buffer protocol that contains types we compare/search by byte equality now can all go through one common path

Comment thread Objects/memoryobject.c
Py_ssize_t i;
int equal;

if ((*fmt == 'B' || *fmt == 'b' || *fmt == 'c') &&

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.

One of the reasons this is so fast, is that the for loop below (the fallback) is fairly inefficient. A prototype to improve that:

main...eendebakpt:memoryview-cmp-typed-loops

(which works for all types, not just B/b/c and for more strides)

I suspect that even then the memcpy here is faster so this might still be good to do, but the margin will be smaller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Speed up equality comparisons between contiguous byte memoryviews with memcmp()

3 participants