summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDong-hee Na <donghee.na92@gmail.com>2020-10-21 10:29:14 +0900
committerGitHub <noreply@github.com>2020-10-21 10:29:14 +0900
commit25492a5b59c5b74328278f195540e318ab87674f (patch)
tree4a78df2e9db249b2c35eb6d7c21a334f3d355228
parenta460d45063844a21c20fa8b0d23878165f99f3b5 (diff)
downloadcpython-git-25492a5b59c5b74328278f195540e318ab87674f.tar.gz
bpo-41902: Micro optimization for compute_item of range (GH-22492)
-rw-r--r--Misc/NEWS.d/next/Core and Builtins/2020-10-02-13-32-05.bpo-41902.ZKTxzW.rst3
-rw-r--r--Objects/rangeobject.c16
2 files changed, 14 insertions, 5 deletions
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 0000000000..b118a6a36f
--- /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 ba6d425717..eaa48d5f44 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;
}