From: Michael Edgar Date: 2011-08-08T00:20:32+09:00 Subject: Re: Methods defined with module_eval are... faster? On Aug 7, 2011, at 11:01 AM, Chris White wrote: > Yes that's correct. In order to understand the logic it's important to take a look at the resulting bytecode, as benchmarks can get a little weird. First the non-module_eval version: > > https://gist.github.com/fc559c8a92336e382777 > > Resulting bytecode: > > https://gist.github.com/1130430 > > As shown here, the method is created, then attached to the module. Now the module_eval version: > > https://gist.github.com/1130424 > > Resulting bytecode: > > https://gist.github.com/1130432 > > Now here, instead of creating a method and attaching it the module, it's instead just putting a string with the code on the stack and sending it off to module_eval. This hits the C side of ruby in the following manner: > > https://gist.github.com/1130437 > > So in essence it means more time is spent in the C side instead of a back and forth chain of bytecode calls. Note that all bytecode is produced via MRI 1.9.3. Honestly though the difference between the two using the benchmark was minimal enough that I don't think it's anything to be worried over. Also note that syntax highlighters will see the eval string as what it is, a literal string. This will make your code less readable! This doesn't explain at all why running the method `kk` is faster, it explains why the small snippet *creating* the method `kk` might be faster than creating the method `aa`. You didn't show and compare the bytecode of the method `kk` after it had been compiled by module_eval, which is what is actually run by the loop and is measured to be faster than the bytecode inside `aa`. Michael Edgar adgar@carboni.ca http://carboni.ca/