Skip to content

Commit 32fe0cc

Browse files
eendebakptserhiy-storchakaerlend-aaslandStanFromIreland
authored
gh-116477: Improve performance of range() when start is 0 and step is 1 (#116478)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com> Co-authored-by: Erlend E. Aasland <erlend.aasland@protonmail.com> Co-authored-by: Stan Ulbrych <stan@python.org>
1 parent 6632294 commit 32fe0cc

2 files changed

Lines changed: 9 additions & 0 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Speed up the :class:`range` object constructor in the case of a single argument.

‎Objects/rangeobject.c‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,14 @@ compute_range_length(PyObject *start, PyObject *stop, PyObject *step)
259259
assert(PyLong_Check(stop));
260260
assert(PyLong_Check(step));
261261

262+
/* fast path for start == 0 and step == 1: length is max(stop, 0) */
263+
if (start == zero && step == one) {
264+
if (_PyLong_IsPositive((const PyLongObject *)stop)) {
265+
return Py_NewRef(stop);
266+
}
267+
return zero;
268+
}
269+
262270
/* fast path when all arguments fit into a long integer */
263271
long len = compute_range_length_long(start, stop, step);
264272
if (len >= 0) {

0 commit comments

Comments
 (0)