bpo-47009: Streamline list.append for the common case (GH-31864) · python/cpython@a0ea7a1 (original) (raw)
`@@ -301,26 +301,27 @@ PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
`
301
301
`return ins1((PyListObject *)op, where, newitem);
`
302
302
`}
`
303
303
``
304
``
`-
static int
`
305
``
`-
app1(PyListObject *self, PyObject *v)
`
``
304
`+
/* internal, used by _PyList_AppendTakeRef */
`
``
305
`+
int
`
``
306
`+
_PyList_AppendTakeRefListResize(PyListObject *self, PyObject *newitem)
`
306
307
`{
`
307
``
`-
Py_ssize_t n = PyList_GET_SIZE(self);
`
308
``
-
309
``
`-
assert (v != NULL);
`
310
``
`-
assert((size_t)n + 1 < PY_SSIZE_T_MAX);
`
311
``
`-
if (list_resize(self, n+1) < 0)
`
``
308
`+
Py_ssize_t len = PyList_GET_SIZE(self);
`
``
309
`+
assert(self->allocated == -1 || self->allocated == len);
`
``
310
`+
if (list_resize(self, len + 1) < 0) {
`
``
311
`+
Py_DECREF(newitem);
`
312
312
`return -1;
`
313
``
-
314
``
`-
Py_INCREF(v);
`
315
``
`-
PyList_SET_ITEM(self, n, v);
`
``
313
`+
}
`
``
314
`+
PyList_SET_ITEM(self, len, newitem);
`
316
315
`return 0;
`
317
316
`}
`
318
317
``
319
318
`int
`
320
319
`PyList_Append(PyObject *op, PyObject *newitem)
`
321
320
`{
`
322
``
`-
if (PyList_Check(op) && (newitem != NULL))
`
323
``
`-
return app1((PyListObject *)op, newitem);
`
``
321
`+
if (PyList_Check(op) && (newitem != NULL)) {
`
``
322
`+
Py_INCREF(newitem);
`
``
323
`+
return _PyList_AppendTakeRef((PyListObject *)op, newitem);
`
``
324
`+
}
`
324
325
`PyErr_BadInternalCall();
`
325
326
`return -1;
`
326
327
`}
`
`@@ -844,9 +845,10 @@ static PyObject *
`
844
845
`list_append(PyListObject *self, PyObject *object)
`
845
846
`/[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]/
`
846
847
`{
`
847
``
`-
if (app1(self, object) == 0)
`
848
``
`-
Py_RETURN_NONE;
`
849
``
`-
return NULL;
`
``
848
`+
if (_PyList_AppendTakeRef(self, Py_NewRef(object)) < 0) {
`
``
849
`+
return NULL;
`
``
850
`+
}
`
``
851
`+
Py_RETURN_NONE;
`
850
852
`}
`
851
853
``
852
854
`/*[clinic input]
`
`@@ -963,9 +965,7 @@ list_extend(PyListObject *self, PyObject *iterable)
`
963
965
`Py_SET_SIZE(self, Py_SIZE(self) + 1);
`
964
966
` }
`
965
967
`else {
`
966
``
`-
int status = app1(self, item);
`
967
``
`-
Py_DECREF(item); /* append creates a new ref */
`
968
``
`-
if (status < 0)
`
``
968
`+
if (_PyList_AppendTakeRef(self, item) < 0)
`
969
969
` goto error;
`
970
970
` }
`
971
971
` }
`