Skip to content

Instantly share code, notes, and snippets.

@joshuap
Created March 6, 2015 20:00
Show Gist options
  • Select an option

  • Save joshuap/2e420730b8183da4aed0 to your computer and use it in GitHub Desktop.

Select an option

Save joshuap/2e420730b8183da4aed0 to your computer and use it in GitHub Desktop.
Object allocations when calling block parameter vs. yielding implicitly.
require 'allocation_stats'
GROUP_BY = [:sourcefile, :sourceline, :class]
def block_without_param
yield
end
def block_with_param(&block)
block.call
end
stats = AllocationStats.trace do
50.times { block_without_param { 'foo' } }
50.times { block_with_param { 'foo' } }
end
puts stats.allocations(alias_paths: true).group_by(*GROUP_BY).to_text
~/code » ruby -v
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
~/code » ruby block_allocations.rb
sourcefile sourceline class count
-------------------- ---------- ----------- -----
block_allocations.rb 15 String 50
block_allocations.rb 15 Proc 50
block_allocations.rb 15 RubyVM::Env 51
block_allocations.rb 14 String 50
@unixsuperhero
Copy link

sorry to hijack your gist. someone showed this to me, here was my reply...

but yeah, it makes sense that the proc is being defined. because it's instantiating a new variable, block, and assigning a value to it (the proc)
when calling it implicity, it already has a place in memory

the place in memory is the { 'foo' } on line 14

@joshuap
Copy link
Author

joshuap commented Mar 10, 2015

That's interesting; so are you saying it's waiting to do the memory assignment until after the method call on line 15, when it creates the variable for the parameter in block_with_param? Isn't the fact that one adds an object to ObjectSpace and one (apparently) doesn't still create some extra overhead during garbage collection?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment