Skip to content
Closed
Changes from 4 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
21 changes: 14 additions & 7 deletions Objects/memoryobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3310,6 +3310,8 @@ typedef struct {
static PyObject *
memoryiter_new(PyObject *self, int reversed)
{
assert(reversed == 0 || reversed == 1);

if (!PyMemoryView_Check(self)) {
PyErr_BadInternalCall();
return NULL;
Expand Down Expand Up @@ -3343,7 +3345,7 @@ memoryiter_new(PyObject *self, int reversed)
it->it_index = reversed ? (it->it_length - 1) : 0;
it->it_seq = _PyMemoryView_CAST(Py_NewRef(self));
_PyObject_GC_TRACK(it);
return (PyObject *)it;
return _PyObject_CAST(it);
}

static void
Expand Down Expand Up @@ -3403,9 +3405,7 @@ PyTypeObject _PyMemoryIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
.tp_name = "memory_iterator",
.tp_basicsize = sizeof(memoryiterobject),
// methods
.tp_dealloc = memoryiter_dealloc,
.tp_getattro = PyObject_GenericGetAttr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = memoryiter_traverse,
.tp_iter = PyObject_SelfIter,
Expand Down Expand Up @@ -3443,22 +3443,29 @@ static PyObject *
memoryview___reversed___impl(PyMemoryViewObject *self)
/*[clinic end generated code: output=25f9b4345f4720ad input=3c35e9267ad7fcc6]*/
{
return memoryiter_new((PyObject *)self, 1);
// NOTE(picnixz): generic implementation via reversed(...) is faster
// if the iterator is not used or if zero or few items are iterated.
//
// When the number of items is sufficiently large (>= 2^5), benchmarks
// show that this implementation improves for-loop performances. Note
// that materializing the specialized reversed iterator is likely to
// be slower than materializing a generic reversed object instance.
return memoryiter_new(_PyObject_CAST(self), 1);
}


PyTypeObject _PyMemoryRevIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"memory_reverseiterator",
sizeof(memoryiterobject),
.tp_name = "memory_reverseiterator",
.tp_basicsize = sizeof(memoryiterobject),
.tp_dealloc = memoryiter_dealloc,
.tp_getattro = PyObject_GenericGetAttr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = memoryiter_traverse,
.tp_iter = PyObject_SelfIter,
.tp_iternext = memorview_reverse_iternext,
};


PyTypeObject PyMemoryView_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"memoryview", /* tp_name */
Expand Down
Loading