summaryrefslogtreecommitdiff
path: root/py/objint_mpz.c
diff options
context:
space:
mode:
authorJim Mussared <jim.mussared@gmail.com>2022-10-06 13:44:54 +1100
committerDamien George <damien@micropython.org>2024-07-01 13:52:59 +1000
commit557d31ed2c75e90b2f2c534c7019cb51aab5a7c8 (patch)
tree1a76c8cbbc1863a167d4f52bfbe73cc34f487191 /py/objint_mpz.c
parent0600e4f27333092884358c967123dcc040d7a1cc (diff)
py/objint: Try to convert big-int back to small-int after binary op.
Before this change, long/mpz ints propagated into all future calculations, even if their value could fit in a small-int object. With this change, the result of a big-int binary op will now be converted to a small-int object if the value fits in a small-int. For example, a relatively common operation like `x = a * b // c` where a,b,c all small ints would always result in a long/mpz int, even if it didn't need to, and then this would impact all future calculations with x. This adds +24 bytes on PYBV11 but avoids heap allocations and potential surprises (e.g. `big-big` is now a small `0`, and can safely be accessed with MP_OBJ_SMALL_INT_VALUE). Performance tests are unchanged on PYBV10, except for `bm_pidigits.py` which makes heavy use of big-ints and gains about 8% in speed. Unix coverage tests have been updated to cover mpz code that is now unreachable by normal Python code (removing the unreachable code would lead to some surprising gaps in the internal C functions and the functionality may be needed in the future, so it is kept because it has minimal overhead). This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
Diffstat (limited to 'py/objint_mpz.c')
-rw-r--r--py/objint_mpz.c12
1 files changed, 12 insertions, 0 deletions
diff --git a/py/objint_mpz.c b/py/objint_mpz.c
index 4a1a685bb..6f2ea616c 100644
--- a/py/objint_mpz.c
+++ b/py/objint_mpz.c
@@ -312,6 +312,14 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i
return MP_OBJ_NULL; // op not supported
}
+ // Check if the result fits in a small-int, and if so just return that.
+ mp_int_t res_small;
+ if (mpz_as_int_checked(&res->mpz, &res_small)) {
+ if (MP_SMALL_INT_FITS(res_small)) {
+ return MP_OBJ_NEW_SMALL_INT(res_small);
+ }
+ }
+
return MP_OBJ_FROM_PTR(res);
} else {
@@ -425,6 +433,10 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t value;
if (mpz_as_int_checked(&self->mpz, &value)) {
+ // mp_obj_int_t objects should always contain a value that is a large
+ // integer (if the value fits in a small-int then it should have been
+ // converted to a small-int object), and so this code-path should never
+ // be taken in normal circumstances.
return value;
} else {
// overflow