]> granicus.if.org Git - python/commitdiff
bpo-34303: Micro-optimizations in functools.reduce() (GH-8598)
authorSergey Fedoseev <fedoseev.sergey@gmail.com>
Sat, 1 Jun 2019 20:32:18 +0000 (01:32 +0500)
committerRaymond Hettinger <rhettinger@users.noreply.github.com>
Sat, 1 Jun 2019 20:32:17 +0000 (13:32 -0700)
Misc/NEWS.d/next/Library/2018-08-03-09-47-20.bpo-34303.tOE2HP.rst [new file with mode: 0644]
Modules/_functoolsmodule.c

diff --git a/Misc/NEWS.d/next/Library/2018-08-03-09-47-20.bpo-34303.tOE2HP.rst b/Misc/NEWS.d/next/Library/2018-08-03-09-47-20.bpo-34303.tOE2HP.rst
new file mode 100644 (file)
index 0000000..94c1299
--- /dev/null
@@ -0,0 +1,2 @@
+Performance of :func:`functools.reduce` is slightly improved. Patch by
+Sergey Fedoseev.
index aca5bad23f585ba8ee1c8e3e654eb0077f0f267f..a101363bf02a07dedfa3184a52fc42c46bbb660c 100644 (file)
@@ -626,10 +626,13 @@ functools_reduce(PyObject *self, PyObject *args)
         if (result == NULL)
             result = op2;
         else {
-            PyTuple_SetItem(args, 0, result);
-            PyTuple_SetItem(args, 1, op2);
-            if ((result = PyEval_CallObject(func, args)) == NULL)
+            /* Update the args tuple in-place */
+            assert(args->ob_refcnt == 1);
+            Py_XSETREF(_PyTuple_ITEMS(args)[0], result);
+            Py_XSETREF(_PyTuple_ITEMS(args)[1], op2);
+            if ((result = PyObject_Call(func, args, NULL)) == NULL) {
                 goto Fail;
+            }
         }
     }