Skip to content

Commit c9cf019

Browse files
eendebakptskirpichevvstinnerserhiy-storchaka
authored
gh-136599: Improve long_hash() (#136600)
Co-authored-by: Sergey B Kirpichev <[email protected]> Co-authored-by: Victor Stinner <[email protected]> Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent e46d403 commit c9cf019

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve performance of :class:`int` hash calculations.

Objects/longobject.c

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3676,7 +3676,23 @@ long_hash(PyObject *obj)
36763676
}
36773677
i = _PyLong_DigitCount(v);
36783678
sign = _PyLong_NonCompactSign(v);
3679-
x = 0;
3679+
3680+
// unroll first digit
3681+
Py_BUILD_ASSERT(PyHASH_BITS > PyLong_SHIFT);
3682+
assert(i >= 1);
3683+
--i;
3684+
x = v->long_value.ob_digit[i];
3685+
assert(x < PyHASH_MODULUS);
3686+
3687+
#if PyHASH_BITS >= 2 * PyLong_SHIFT
3688+
// unroll second digit
3689+
assert(i >= 1);
3690+
--i;
3691+
x <<= PyLong_SHIFT;
3692+
x += v->long_value.ob_digit[i];
3693+
assert(x < PyHASH_MODULUS);
3694+
#endif
3695+
36803696
while (--i >= 0) {
36813697
/* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
36823698
want to compute x * 2**PyLong_SHIFT + v->long_value.ob_digit[i] modulo

0 commit comments

Comments
 (0)