Class: Hone::Patterns::LazyIvar

Inherits:
Base
  • Object
show all
Defined in:
lib/hone/patterns/lazy_ivar.rb

Overview

Pattern: @ivar ||= value (outside initialize)

When an ivar is first assigned outside initialize, it changes the object's shape at runtime. YJIT prefers stable shapes from creation.

This pattern detects ||= with ivars outside of initialize methods.

Impact: Moderate with YJIT, none without

Instance Attribute Summary

Attributes inherited from Base

#findings

Instance Method Summary collapse

Methods inherited from Base

#add_finding, inherited, scan_file

Constructor Details

#initialize(file_path) ⇒ LazyIvar

Returns a new instance of LazyIvar.



17
18
19
20
# File 'lib/hone/patterns/lazy_ivar.rb', line 17

def initialize(file_path)
  super
  @in_initialize = false
end

Instance Method Details

#visit_def_node(node) ⇒ Object



22
23
24
# File 'lib/hone/patterns/lazy_ivar.rb', line 22

def visit_def_node(node)
  with_context(:@in_initialize, node.name == :initialize) { super }
end

#visit_instance_variable_or_write_node(node) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/hone/patterns/lazy_ivar.rb', line 26

def visit_instance_variable_or_write_node(node)
  super
  # @ivar ||= value pattern
  return if @in_initialize

  add_finding(
    node,
    message: "Lazy ivar initialization (||=) outside initialize causes shape transitions. Define #{node.name} = nil in initialize for better YJIT.",
    speedup: "Moderate with YJIT, none without"
  )
end