Skip to content

Commit 25492a5

Browse files
authored
bpo-41902: Micro optimization for compute_item of range (GH-22492)
1 parent a460d45 commit 25492a5

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Micro optimization when compute :c:member:`~PySequenceMethods.sq_item` and
2+
:c:member:`~PyMappingMethods.mp_subscript` of :class:`range`. Patch by
3+
Dong-hee Na.

Objects/rangeobject.c

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -254,11 +254,17 @@ compute_item(rangeobject *r, PyObject *i)
254254
/* PyLong equivalent to:
255255
* return r->start + (i * r->step)
256256
*/
257-
incr = PyNumber_Multiply(i, r->step);
258-
if (!incr)
259-
return NULL;
260-
result = PyNumber_Add(r->start, incr);
261-
Py_DECREF(incr);
257+
if (r->step == _PyLong_One) {
258+
result = PyNumber_Add(r->start, i);
259+
}
260+
else {
261+
incr = PyNumber_Multiply(i, r->step);
262+
if (!incr) {
263+
return NULL;
264+
}
265+
result = PyNumber_Add(r->start, incr);
266+
Py_DECREF(incr);
267+
}
262268
return result;
263269
}
264270

0 commit comments

Comments
 (0)