Class: Hone::Patterns::YieldVsBlock
- Defined in:
- lib/hone/patterns/yield_vs_block.rb
Overview
Pattern: block.call -> yield when method has &block parameter
When a method accepts a block with &block, calling block.call is slower
than using yield. The &block syntax converts the block to a Proc object,
which has overhead. Using yield avoids this Proc allocation when the block
is only called (not stored or passed elsewhere).
Example:
# Before - allocates Proc
def process(&block)
block.call(value)
end
# After - no Proc allocation
def process
yield(value)
end
Impact: Avoids Proc allocation
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
-
#initialize(file_path) ⇒ YieldVsBlock
constructor
A new instance of YieldVsBlock.
- #visit_call_node(node) ⇒ Object
- #visit_def_node(node) ⇒ Object
Methods inherited from Base
#add_finding, inherited, scan_file
Constructor Details
#initialize(file_path) ⇒ YieldVsBlock
Returns a new instance of YieldVsBlock.
28 29 30 31 |
# File 'lib/hone/patterns/yield_vs_block.rb', line 28 def initialize(file_path) super @block_param_name = nil end |
Instance Method Details
#visit_call_node(node) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/hone/patterns/yield_vs_block.rb', line 43 def visit_call_node(node) super return unless @block_param_name return unless node.name == :call receiver = node.receiver return unless receiver.is_a?(Prism::LocalVariableReadNode) return unless receiver.name == @block_param_name add_finding( node, message: "Use `yield` instead of `#{@block_param_name}.call` to avoid Proc allocation", speedup: "Avoids Proc allocation" ) end |
#visit_def_node(node) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/hone/patterns/yield_vs_block.rb', line 33 def visit_def_node(node) block_param = find_block_parameter(node.parameters) if block_param with_context(:@block_param_name, block_param) { super } else super end end |