From d33815a3bceaca54b62986a9d92e4145e0c39ce4 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Mon, 20 Sep 2021 10:07:54 +0200 Subject: [PATCH 1/3] bpo-24076: Inline single digit unpacking in the integer fastpath of sum(). --- Python/bltinmodule.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 76c9f87fdf18a8..b4a8550c4a3c5e 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -2479,7 +2479,14 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start) return PyLong_FromLong(i_result); } if (PyLong_CheckExact(item) || PyBool_Check(item)) { - long b = PyLong_AsLongAndOverflow(item, &overflow); + long b; + overflow = 0; + switch (Py_SIZE(item)) { + case -1: b = -(sdigit) ((PyLongObject*)item)->ob_digit[0]; break; + case 0: continue; + case 1: b = ((PyLongObject*)item)->ob_digit[0]; break; + default: b = PyLong_AsLongAndOverflow(item, &overflow); break; + } if (overflow == 0 && (i_result >= 0 ? (b <= LONG_MAX - i_result) : (b >= LONG_MIN - i_result))) From f9a17dbff23e156c71139c2c976d9148b3dbe9d1 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Mon, 20 Sep 2021 10:17:27 +0200 Subject: [PATCH 2/3] Add News entry. --- .../Core and Builtins/2021-09-20-10-02-12.bpo-24076.ZFgFSj.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2021-09-20-10-02-12.bpo-24076.ZFgFSj.rst diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-09-20-10-02-12.bpo-24076.ZFgFSj.rst b/Misc/NEWS.d/next/Core and Builtins/2021-09-20-10-02-12.bpo-24076.ZFgFSj.rst new file mode 100644 index 00000000000000..b680884ff8b1e0 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2021-09-20-10-02-12.bpo-24076.ZFgFSj.rst @@ -0,0 +1 @@ +sum() was further optimised for summing up single digit integers. From 125cdcf504a5d937b575cda3552b233dd44ba127 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Mon, 20 Sep 2021 10:29:45 +0200 Subject: [PATCH 3/3] Add a comment. --- Python/bltinmodule.c | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index b4a8550c4a3c5e..38bdfb2766f3df 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -2481,6 +2481,7 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start) if (PyLong_CheckExact(item) || PyBool_Check(item)) { long b; overflow = 0; + /* Single digits are common, fast, and cannot overflow on unpacking. */ switch (Py_SIZE(item)) { case -1: b = -(sdigit) ((PyLongObject*)item)->ob_digit[0]; break; case 0: continue;