Skip to content

Commit d80066a

Browse files
committed
Speedup Integer + int
1 parent 5c8d9e9 commit d80066a

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

src/sage/rings/integer.pyx

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,16 @@ cdef inline Integer move_integer_from_mpz(mpz_t x):
430430
``x`` will not be cleared;
431431
432432
- if ``sig_on()`` does not throw, :func:`move_integer_from_mpz` will call ``mpz_clear(x)``.
433+
434+
Note that this is in fact slightly slower than ::
435+
436+
cdef Integer x = <Integer>PY_NEW(Integer)
437+
mpz_SOMETHING_MUTATE_X(x.value, ...)
438+
return x
439+
440+
because with ``move_integer_from_mpz``, one need to allocate a new ``mpz_t``, even if
441+
the ``x`` returned by ``PY_NEW`` already have an allocated buffer (see :func:`fast_tp_new`).
442+
Only use this when interruptibility is required.
433443
"""
434444
cdef Integer y = <Integer>PY_NEW(Integer)
435445
mpz_swap(y.value, x)
@@ -1822,16 +1832,25 @@ cdef class Integer(sage.structure.element.EuclideanDomainElement):
18221832
sage: 1 + (-2/3)
18231833
1/3
18241834
"""
1835+
# because of c_api_binop_methods, either left or right is Integer
18251836
cdef Integer x
18261837
cdef Rational y
18271838
if type(left) is type(right):
1828-
x = <Integer>PY_NEW(Integer)
1829-
mpz_add(x.value, (<Integer>left).value, (<Integer>right).value)
1830-
return x
1839+
return (<Integer> left)._add_(right)
18311840
elif type(right) is Rational:
18321841
y = <Rational>PY_NEW(Rational)
18331842
mpq_add_z(y.value, (<Rational>right).value, (<Integer>left).value)
18341843
return y
1844+
elif type(right) is int:
1845+
x = <Integer>PY_NEW(Integer)
1846+
mpz_set_pylong(x.value, right)
1847+
mpz_add(x.value, (<Integer>left).value, x.value)
1848+
return x
1849+
elif type(left) is int:
1850+
x = <Integer>PY_NEW(Integer)
1851+
mpz_set_pylong(x.value, left)
1852+
mpz_add(x.value, x.value, (<Integer>right).value)
1853+
return x
18351854

18361855
return coercion_model.bin_op(left, right, operator.add)
18371856

0 commit comments

Comments
 (0)