Skip to content

Struct.new in LowType.config allocates a new anonymous class on every call #35

@obsidiannnn

Description

@obsidiannnn

Problem

In low_type.rb, the config method is defined as:

def config
  config = Struct.new(:type_checking, ...)
  @config ||= config.new(true, ...)
end

Struct.new(...) runs on every invocation of LowType.config , it only memoizes the instance via @config ||=, not the Struct class itself. Every call allocates a new anonymous Struct class that is immediately discarded.

Impact

LowType.config.type_checking is called on every method redefine. In a library where minimal overhead is a core goal, allocating and discarding an anonymous class on every config access is real unnecessary work ... minor but avoidable.

Reproduction

# Every call to LowType.config allocates a new Struct class
LowType.config  # => allocates Struct class, discards it, returns memoized instance
LowType.config  # => allocates another Struct class, discards it, returns memoized instance

Proposed Fix

Hoist the Struct definition to a constant so it is created once:

Config = Struct.new(:type_checking, ...)

def config
  @config ||= Config.new(true, ...)
end

This allocates the Struct class once at load time and memoizes both the class and the instance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions