This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author vstinner
Recipients mark.dickinson, vstinner
Date 2014-07-11.09:10:27
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1405069827.92.0.324101531394.issue21955@psf.upfronthosting.co.za>
In-reply-to
Content
Python 2 has fast path in ceval.c for operations (a+b, a-b, etc.) on small integers ("int" type) if the operation does not overflow.

We loose these fast-path in Python 3 when we dropped the int type in favor of the long type.

Antoine Pitrou proposed a fast-path, but only for int singletons (integers in the range [-5; 255]): issue #10044. His patch was rejected because it introduces undefined behaviour.

I propose to reimplemenet Python 2 optimization for long with a single digit, which are the most common numbers.

Pseudo-code for BINARY_ADD:
---
if (PyLong_CheckExact(x) && Py_ABS(Py_SIZE(x)) == 1
    && PyLong_CheckExact(y) && Py_ABS(Py_SIZE(y)) == 1)
{
   stwodigits a = ..., b = ...;
   stwodigits c;
   if (... a+b will not overflow ...) { 
      c = a + b;
      return PyLong_FromLongLong(c);
   }
}
/* fall back to PyNumber_Add() */
---

The code can be copied from longobject.c, there are already fast-path for single digit numbers. See for example long_mul():
---
    /* fast path for single-digit multiplication */
    if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
        ....
    }
---

As any other optimization, it should be proved to be faster with benchmarks.
History
Date User Action Args
2014-07-11 09:10:28vstinnersetrecipients: + vstinner, mark.dickinson
2014-07-11 09:10:27vstinnersetmessageid: <1405069827.92.0.324101531394.issue21955@psf.upfronthosting.co.za>
2014-07-11 09:10:27vstinnerlinkissue21955 messages
2014-07-11 09:10:27vstinnercreate