Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use faster any_hash logic in rb_hash #4916

Merged
merged 1 commit into from
Sep 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions benchmark/hash_aref_array.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
h = {}
arrays = (0..99).each_slice(10).to_a
#STDERR.puts arrays.inspect
arrays.each { |s| h[s] = s }
200_000.times { arrays.each { |s| h[s] } }
59 changes: 30 additions & 29 deletions hash.c
Original file line number Diff line number Diff line change
Expand Up @@ -122,33 +122,6 @@ hash_recursive(VALUE obj, VALUE arg, int recurse)
return rb_funcallv(obj, id_hash, 0, 0);
}

VALUE
rb_hash(VALUE obj)
{
VALUE hval = rb_check_funcall_basic_kw(obj, id_hash, rb_mKernel, 0, 0, 0);

if (hval == Qundef) {
hval = rb_exec_recursive_outer(hash_recursive, obj, 0);
}

while (!FIXNUM_P(hval)) {
if (RB_BIGNUM_TYPE_P(hval)) {
int sign;
unsigned long ul;
sign = rb_integer_pack(hval, &ul, 1, sizeof(ul), 0,
INTEGER_PACK_NATIVE_BYTE_ORDER);
if (sign < 0) {
hval = LONG2FIX(ul | FIXNUM_MIN);
}
else {
hval = LONG2FIX(ul & FIXNUM_MAX);
}
}
hval = rb_to_int(hval);
}
return hval;
}

static long rb_objid_hash(st_index_t index);

static st_index_t
Expand Down Expand Up @@ -216,8 +189,29 @@ any_hash(VALUE a, st_index_t (*other_func)(VALUE))
static st_index_t
obj_any_hash(VALUE obj)
{
obj = rb_hash(obj);
return FIX2LONG(obj);
VALUE hval = rb_check_funcall_basic_kw(obj, id_hash, rb_mKernel, 0, 0, 0);

if (hval == Qundef) {
hval = rb_exec_recursive_outer(hash_recursive, obj, 0);
}

while (!FIXNUM_P(hval)) {
if (RB_TYPE_P(hval, T_BIGNUM)) {
int sign;
unsigned long ul;
sign = rb_integer_pack(hval, &ul, 1, sizeof(ul), 0,
INTEGER_PACK_NATIVE_BYTE_ORDER);
if (sign < 0) {
hval = LONG2FIX(ul | FIXNUM_MIN);
}
else {
hval = LONG2FIX(ul & FIXNUM_MAX);
}
}
hval = rb_to_int(hval);
}

return FIX2LONG(hval);
}

static st_index_t
Expand All @@ -226,6 +220,13 @@ rb_any_hash(VALUE a)
return any_hash(a, obj_any_hash);
}

VALUE
rb_hash(VALUE obj)
{
return LONG2FIX(any_hash(obj, obj_any_hash));
}


/* Here is a hash function for 64-bit key. It is about 5 times faster
(2 times faster when uint128 type is absent) on Haswell than
tailored Spooky or City hash function can be. */
Expand Down