From 13b3d74340a90435fcb2d82c222c358ec31b1582 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 17 Feb 2023 12:03:40 -0800 Subject: [PATCH] Store functions in a hash rather than class variables Setting class variables will mutate the shape of the receiver, causing more inline cache polymorphism than necessary. Storing functions in a hash would better serve the intended functionality, and also benefit runtime performance --- ext/ffi_c/Function.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/ext/ffi_c/Function.c b/ext/ffi_c/Function.c index 1a575911c..56adfc90a 100644 --- a/ext/ffi_c/Function.c +++ b/ext/ffi_c/Function.c @@ -395,10 +395,15 @@ function_attach(VALUE self, VALUE module, VALUE name) } /* - * Stash the Function in a module variable so it does not get garbage collected + * Stash the Function in a hash so it does not get garbage collected */ - snprintf(var, sizeof(var), "@@%s", StringValueCStr(name)); - rb_cv_set(module, var, self); + VALUE funcs = rb_const_get(module, rb_intern("FFI_FUNCTIONS")); + if (NIL_P(funcs)) { + funcs = rb_hash_new(); + rb_const_set(module, rb_intern("FFI_FUNCTIONS"), funcs); + } + + rb_hash_aset(funcs, name, self); rb_define_singleton_method(module, StringValueCStr(name), rbffi_MethodHandle_CodeAddress(fn->methodHandle), -1);