From: Jeremy Bopp Date: 2010-10-08T07:55:53+09:00 Subject: Re: Benchmarks Project and example for `||=` On 10/7/2010 5:11 PM, Intransition wrote: > > > On Oct 7, 12:45 pm, Rick DeNatale wrote: >> On Thu, Oct 7, 2010 at 12:05 PM, Jeremy Bopp wrote: >>> The point of comparison profiling like this is to find ways to improve >>> your code without changing its ultimate function. Your comparison here >>> compares two fundamentally different operations >> >> It struck me as odd that Trans is benchmarking two different things >> against each other. >> >> As another example, I just benchmarked the time it takes me to get up >> out of my sofa and walk to my front door and back at about 30 seconds. >> That's over 3 times FASTER than Fernando Alonso's fastest lap of >> 1:47.976 in the Singapore Grand Prix a couple of Sunday's ago. >> >> So does that make me faster than a Ferrari F10, I don't think so, and >> I doubt that it has a practical significance. > > I think this is a good a reminder as any that it's hard to see what > someone else is getting at when you're not seeing the use case. There > is in fact a very good reason for my comparison. I often do: > > class X > def f > @f ||= ( do_some_calc_or_lookup ) > end > end > > I like this idiom as it provides the speed bump of caching and yet > encapsulates the entire procedure for getting the value in one place. > However, if I am really concerned about squeezing out every bit of > speed, I would do: > > class X > def initialize > @f = ( do_some_calc_or_lookup ) > end > def f > @f > end > end > > The purpose of the benchmark was to see just how much "squeeze" I am > getting in the exchange. Take a look at http://ruby-doc.org/docs/ProgrammingRuby/html/classes.html. On that page you'll find some examples for defining a method named "once". Search for "ExampleDate.once" under the Class and Module Definitions section. You can use the "once" method as a directive that will ensure that a given method which may be expensive to compute is only run 1 time after which the cached value will be returned. I made a generalized version of "once" as suggested there for use in an internal project where I work. That way I get the best of delayed computation, clear code, and fast results for a few methods that really need it. It might be interesting to profile the performance of a method wrapped by "once" compared to your other solutions. -Jeremy