Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Lib/test/test_memoryview.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,16 @@ def _check_contents(self, tp, obj, contents):
class BytesMemoryviewTest(unittest.TestCase,
BaseMemoryviewTests, BaseBytesMemoryTests):

def test_compare_byte_views(self):
for fmt in ('B', 'b', 'c'):
with self.subTest(format=fmt):
packed = memoryview(b'ab').cast(fmt)
spaced = memoryview(b'axb').cast(fmt)[::2]
self.assertEqual(packed, spaced)
self.assertEqual(spaced, packed)
self.assertEqual(packed, memoryview(bytearray(b'ab')).cast(fmt))
self.assertNotEqual(packed, memoryview(b'ax').cast(fmt))

def test_comparison_release_during_buffer_callback(self):
# Releasing the view from inside the other operand's __buffer__
# succeeds, but the buffer stays pinned until the comparison ends:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up :class:`memoryview` equality comparisons for contiguous buffers with
matching byte formats. Patch by Maurycy Pawłowski-Wieroński.
7 changes: 7 additions & 0 deletions Objects/memoryobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3444,6 +3444,13 @@ cmp_base(const char *p, const char *q, const Py_ssize_t *shape,
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.

pstrides[0] == 1 && qstrides[0] == 1 &&
psuboffsets == NULL && qsuboffsets == NULL && shape[0] > 0)
{
return memcmp(p, q, shape[0]) == 0;
}

for (i = 0; i < shape[0]; p+=pstrides[0], q+=qstrides[0], i++) {
const char *xp = ADJUST_PTR(p, psuboffsets, 0);
const char *xq = ADJUST_PTR(q, qsuboffsets, 0);
Expand Down
Loading