[Python-checkins] bpo-41902: Micro optimization for compute_item of range (GH-22492)

methane webhook-mailer at python.org
Tue Oct 20 21:29:22 EDT 2020


https://github.com/python/cpython/commit/25492a5b59c5b74328278f195540e318ab87674f
commit: 25492a5b59c5b74328278f195540e318ab87674f
branch: master
author: Dong-hee Na <donghee.na92 at gmail.com>
committer: methane <songofacandy at gmail.com>
date: 2020-10-21T10:29:14+09:00
summary:

bpo-41902: Micro optimization for compute_item of range (GH-22492)

files:
A Misc/NEWS.d/next/Core and Builtins/2020-10-02-13-32-05.bpo-41902.ZKTxzW.rst
M Objects/rangeobject.c

diff --git a/Misc/NEWS.d/next/Core and Builtins/2020-10-02-13-32-05.bpo-41902.ZKTxzW.rst b/Misc/NEWS.d/next/Core and Builtins/2020-10-02-13-32-05.bpo-41902.ZKTxzW.rst
new file mode 100644
index 0000000000000..b118a6a36fae3
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2020-10-02-13-32-05.bpo-41902.ZKTxzW.rst	
@@ -0,0 +1,3 @@
+Micro optimization when compute :c:member:`~PySequenceMethods.sq_item` and
+:c:member:`~PyMappingMethods.mp_subscript` of :class:`range`. Patch by
+Dong-hee Na.
diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c
index ba6d425717495..eaa48d5f44fcc 100644
--- a/Objects/rangeobject.c
+++ b/Objects/rangeobject.c
@@ -254,11 +254,17 @@ compute_item(rangeobject *r, PyObject *i)
     /* PyLong equivalent to:
      *    return r->start + (i * r->step)
      */
-    incr = PyNumber_Multiply(i, r->step);
-    if (!incr)
-        return NULL;
-    result = PyNumber_Add(r->start, incr);
-    Py_DECREF(incr);
+    if (r->step == _PyLong_One) {
+        result = PyNumber_Add(r->start, i);
+    }
+    else {
+        incr = PyNumber_Multiply(i, r->step);
+        if (!incr) {
+            return NULL;
+        }
+        result = PyNumber_Add(r->start, incr);
+        Py_DECREF(incr);
+    }
     return result;
 }
 



More information about the Python-checkins mailing list