Skip to content

Instantly share code, notes, and snippets.

@tenderlove
Created June 4, 2019 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tenderlove/8ea16d341580c02daafca15076ee6771 to your computer and use it in GitHub Desktop.
Save tenderlove/8ea16d341580c02daafca15076ee6771 to your computer and use it in GitHub Desktop.
# How to measure the size of a method's iseq
require 'objspace'
small_body = (["bar"] * 10).join(" + ")
big_body = (["bar"] * 10_000).join(" + ")
eval "def small(bar); #{small_body}; end"
eval "def big(bar); #{big_body}; end"
small_seq = RubyVM::InstructionSequence.of(method(:small))
big_seq = RubyVM::InstructionSequence.of(method(:big))
puts ObjectSpace.memsize_of(small_seq)
puts ObjectSpace.memsize_of(big_seq)
# Ruby 2.5 will show the "mark array", where Ruby 2.6 will not
imemo = ObjectSpace.reachable_objects_from(big_seq).last
p imemo # IMEMO is the actual iseqs, where the InstructionSequence object is a wrapper
# Printing the references for the imemo will show the "mark array" in Ruby 2.5
p ObjectSpace.reachable_objects_from(imemo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment