From 034682ca36f203b225e54803fddbcaf7f04434a8 Mon Sep 17 00:00:00 2001 From: Jeethu Rao Date: Thu, 11 Jan 2018 13:56:07 +0000 Subject: [PATCH] bpo-32534: Speed up in list.insert --- Misc/ACKS | 1 + .../2018-01-16-23-01-29.bpo-32534.fwiEyr.rst | 1 + Objects/listobject.c | 17 +++++++++++++---- 3 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2018-01-16-23-01-29.bpo-32534.fwiEyr.rst diff --git a/Misc/ACKS b/Misc/ACKS index 009b072d680aac..a88f586133aaea 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -1790,3 +1790,4 @@ Jelle Zijlstra Gennadiy Zlobin Doug Zongker Peter Åstrand +Jeethu Rao diff --git a/Misc/NEWS.d/next/Core and Builtins/2018-01-16-23-01-29.bpo-32534.fwiEyr.rst b/Misc/NEWS.d/next/Core and Builtins/2018-01-16-23-01-29.bpo-32534.fwiEyr.rst new file mode 100644 index 00000000000000..d9652255e88d25 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2018-01-16-23-01-29.bpo-32534.fwiEyr.rst @@ -0,0 +1 @@ +Faster list.insert for lists with 32 or more elements in them. Patch by Jeethu Rao. diff --git a/Objects/listobject.c b/Objects/listobject.c index 8794e37364a81f..9a0b5b52120caf 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -234,6 +234,12 @@ PyList_SetItem(PyObject *op, Py_ssize_t i, return 0; } + +/* Threshold at which to switch to using + * memmove instead of a for loop in ins1 + */ +#define INS1_MEMMOVE_THRESHOLD 32 + static int ins1(PyListObject *self, Py_ssize_t where, PyObject *v) { @@ -256,12 +262,15 @@ ins1(PyListObject *self, Py_ssize_t where, PyObject *v) where += n; if (where < 0) where = 0; - } - if (where > n) + } else if (where > n) where = n; items = self->ob_item; - for (i = n; --i >= where; ) - items[i+1] = items[i]; + if (n <= INS1_MEMMOVE_THRESHOLD) + for (i = n; --i >= where; ) + items[i+1] = items[i]; + else + memmove(&items[where+1], &items[where], + sizeof(PyObject*) * (n - where)); Py_INCREF(v); items[where] = v; return 0;