4 ms·
A fun bit of info, you can get access to the method cache data directly from Ruby (in MRI) using `RubyVM.stat`. The variables are not really well named, but he
by tenderlove 12y ago
A fun bit of info, you can get access to the method cache data directly from Ruby (in MRI) using `RubyVM.stat`. The variables are not really well named, but here is a test program to demonstrate the behavior:
class Foo; end
foo = Foo.new
p RubyVM.stat # => {:global_method_state=>133, :global_constant_state=>804, :class_serial=>5486}
# break a classes method cache. :class_serial will increase
foo.extend(Module.new { def bar; end })
p RubyVM.stat # => {:global_method_state=>133, :global_constant_state=>804, :class_serial=>5491}
# break Object's method cache. :global_method_state will increase
class Object
def omb
end
end
p RubyVM.stat # => {:global_method_state=>134, :global_constant_state=>804, :class_serial=>5491}
# break constant cache, :global_constant_state will increase
Object.send :remove_const, :Foo
p RubyVM.stat # => {:global_method_state=>134, :global_constant_state=>805, :class_serial=>5491}
Extending an instance will break the cache for that class. Adding methods to Object will break the global cache. Removing a constant will break the constant cache. I think there are other ways to break the caches, but I can't remember off the top of my head.
Anyway, the point is that you can get access to the information from Ruby, so I'll use this when testing Rails to ensure we aren't breaking caches. Making a Rack middleware to output this info might be handy, or adding it to tests might be a cool project too (like output a warning if a test method breaks the cache or something).
- sshconnection 12y agoDoes OpenStruct still break caches?
- gamache 12y agoIf you're worried about flushing the cache, there's Charlie Somerville's flush-free OpenStruct: https://github.com/charliesome/fast_open_struct https://github.com/charliesome/fast_open_struct
- stanislavb 12y agoThanks! The idea of adding this to tests or a middleware is very good :)
- tmm1 12y agoThe https://github.com/simeonwillbanks/busted https://github.com/simeonwillbanks/busted gem provides some nice helpers around RubyVM.stat for finding cache invalidations. It can also take advantage of the dtrace/systemtap probes that shipped with ruby 2.1 (http://tmm1.net/ruby21-method-cache http://tmm1.net/ruby21-method-cache) which can be used as an alternative to the ftrace technique described in the blog post.