#137 Memoization (revised)
Aug 18, 2012 | 9 minutes | Performance, Caching
Memoization is a convenient way to cache a method's response. Here I show several ways to accomplish this from scratch since the ActiveSupport::Memoizable module has been deprecated.
- Download:
- source code
- mp4
- m4v
- webm
- ogv
Very handy episode! How about one on caching techniques using Memcached, etc? Russian Doll caching seems to be something interesting as well...
@ac74394 http://www.youtube.com/watch?v=FkLVl3gpJP4#t=80m12s
DHH goes into Russian doll caching at a recent meetup he teleconferenced in at.
Would be interesting to see Ryan cover it as well but he does a pretty good job explaining how it works.
Thanks for this link to DHH's presentation. The russian doll caching strategy is really the first I have seen (Rails or otherwise) that doesn't have a big long list of tradeoffs -- they figured out how to make it just work. It's worth backing up to watch all of DHH's stuff. Much of what he talks about is how to get all the benefits of über-responsive client-side performance without completely chucking Rails and moving to Backbone.JS
There are at least three whole topics are performance and caching for Ryan to cover. Memoization as covered here is a tiny little aspect of caching in comparison.
(Update: I am behind on my RailsCasts -- Ryan has done a lot of them already. Go Ryan!)
nice piece, also for the neat metaprogramming example!
NB: playback cuts off a little, missing the last couple of seconds.
Yeah, your playbacks always cut off the last couple of seconds, for me. If nothing else pad it with music that fades out. This way, we will at least hear everything you say and know we've reached the end.
In fact,
a ||= "something"
is equivalent toa = a || "something"
What does this mean?
a = a || "something"
-> left operand ina || "something"
isn't defined, evaluates to nil, which is false, then right operand needs to be evaluated as well, so assigning a value.That's an idiom that came from C language. Try that in irb and you see there's no error at all.
A common misconception is that
a ||= b
is equivalent toa = a || b
, but it actually behaves likea || a = b
.I believe it's logically equivalent to this
a = a ? a : "something"
Which means:
set the value of a to, if there is an 'a', then a, otherwise set it to "something"
I've seen recently a Gem for creating such method encapsulation like memoization. It's called MethodDecorators, inspired by actual decorators existing in Python, you can find it on Github.
It's very interesting because of its extensive usage of metaprogramming and the way author mimics features of another programming language.
demo link
Amazing post.