Yesterday, I published a fairly long article on InfoQ about Evaluation Options in Ruby. The article covers eval, instance_eval, class_eval and provides examples of using each of them.
That was a very interesting read. Thanks for the link.
Umm... could you please (re)explain why your second form of attr_init was better optimized than the first form?
I couldn't understand this: "It was not obvious at first to me, but the following solution is far superior since it only requires one call to eval instead of a new eval with each call to the defined method." To me it seems both forms result in the same number of eval calls. What am I not seeing?
I created an example, but it's a bit long and looks much better on pastie.
http://pastie.caboo.se/46177
If you copy that example and execute it, you'll notice that the call to attr_init_optimized causes an eval to occur; however, all the calls to baz do not require an eval. Conversely, the call to attr_init does not require an eval, but each call to bar causes an eval to occur.
Basically, in the unoptimized case, the eval statement became part of the method you were defining and hence got executed each time the defined method was called; whereas in the optimized case, the eval statement was not part of the defined method itself (as it wasn't within it): the contents of the method were fixed when the method itself was defined using eval. :-) I should have caught that.
That was a very interesting read. Thanks for the link.
ReplyDeleteUmm... could you please (re)explain why your second form of attr_init was better optimized than the first form?
I couldn't understand this: "It was not obvious at first to me, but the following solution is far superior since it only requires one call to eval instead of a new eval with each call to the defined method." To me it seems both forms result in the same number of eval calls. What am I not seeing?
Aman
ReplyDeleteI created an example, but it's a bit long and looks much better on pastie.
http://pastie.caboo.se/46177
If you copy that example and execute it, you'll notice that the call to attr_init_optimized causes an eval to occur; however, all the calls to baz do not require an eval. Conversely, the call to attr_init does not require an eval, but each call to bar causes an eval to occur.
Thanks, Jay! The example helped.
ReplyDeleteBasically, in the unoptimized case, the eval statement became part of the method you were defining and hence got executed each time the defined method was called; whereas in the optimized case, the eval statement was not part of the defined method itself (as it wasn't within it): the contents of the method were fixed when the method itself was defined using eval. :-) I should have caught that.