Project

General

Profile

Actions

Feature #18275

open

Add an option to define_method to not capture the surrounding environment

Added by vinistock (Vinicius Stock) about 3 years ago. Updated 8 months ago.

Status:
Assigned
Target version:
-
[ruby-core:105833]

Description

Invoking define_method will capture the surrounding environment, making sure we have access to anything defined in that surrounding scope. However, that’s not always necessary. There are uses for define_method where the surrounding environment is not needed.

Always capturing the surrounding environment slows down even the methods that don’t need access to it. Additionally, it prevents methods created using define_method to exist in all Ractors in a program.

If we could add an option to disable capturing the surrounding environment for define_method, we could make it so that it creates the dynamic method in all Ractors.

There could also be some performance benefits for the usages that do not need the surrounding environment. By not having to keep references to the surrounding scope, the GC could let go of locals from that environment, which might benefit GC as well.

Another option could be to accept the list of locals that the define_method invocation will need, as a way of letting go of references that are no longer needed.

Examples:

# Current behavior
#
# All of the surrounding environment is captured and references are kept for the locals
# The method created only exists in the current Ractor, due to possible references to the captured variables

some_random_thing = "a" * 10000
some_captured_block = -> { ... }

define_method(:my_method, &some_captured_block)
# Enable/disable all option
#
# Add an option that allows disabling capturing the surrounding environment completely
# The method created exists in all Ractors and none of the references are kept

some_random_thing = "a" * 10000
some_captured_block = -> { ... }

define_method(:my_method, capture_environment: false, &some_captured_block)
# Choose variables option
#
# Add an option that allows indicating which locals are needed for a define_method invocation
# The method created exists in all Ractors if no locals are needed
# The method is created only in the current Ractor if at least one local is needed
# All “unneeded” locals are let go

some_random_thing = "a" * 10000 # kept because `my_method` needs it
another_random_thing = "b" * 10000 # not kept
some_captured_block = -> { ... }

define_method(:my_method, needs: [:some_random_thing], &some_captured_block)
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0