Dynamic Method Definitions
2013-03-03 @ 16:52 Dynamic Method Definitions TL;DR: depending on your app, using define_method is faster on boot, consumes less memory, and probably doesn’t signigicantly impact performance. Throughout the Rails code base, I typically see dynamic methods defined using class_eval . What I mean by “dynamic methods” is methods with names or bodies that are calculated at runtime, then defined. For example, something like this: class Foo class_eval <<EORUBY, __FILE__, __LINE__ + 1 def wow_#{Time.now.to_i} # ... end EORUBY end I’m not sure why they are define this way versus using define_method . Why don’t we compare and contrast defining methods using class_eval and define_method ? The tests I’ll do here use MRI, Ruby 2.0.0. Definition Performance When defining a method, is it faster to use class_eval or define_method ? Here is a trivial benchmark where we simulate defining 10...
Full article:
http://tenderlovemaking.com/2013/03/03/dynamic_method_def...