basic memoization in ruby

Post on 29-Jul-2015

64 Views

Category:

Software

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Basic memoization in

RubyOmbu Labs, April 2015

“Memoization is an optimization technique where

you cache the results of expensive method calls.”

http://nithinbekal.com/posts/ruby-memoization/

Conditional assignment operator

a ||= b

irb(main):001:0> a = 1=> 1irb(main):002:0> a ||= 2=> 1

Not assigned, because a was already set to 1

irb(main):003:0> a = nil=> nilirb(main):004:0> a ||= 2=> 2

Assigned, because a was nil

a ||= b == a || a = b

Without memoization

def current_user User.find(session[:user_id])end

With memoization

def current_user @current_user ||= User.find(session[:user_id])end

When to memoize?

• Duplicate database calls

• Expensive calculations

• Calculations that do not change

When NOT to memoize?

• Some methods that take parameters *

• Calculations that can easily change

* unless you memoize a Hash object

2.1.2 :001 > def say_hi(name)2.1.2 :002?> @greeting ||= "Hello #{name}!"2.1.2 :003?> end => :say_hi 2.1.2 :004 > say_hi("John") => "Hello John!" 2.1.2 :005 > say_hi("You") => "Hello John!"

Real use case

CACHE (0.0ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT 1 [["id", 3]]CACHE (0.1ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT 1 [["id", 3]]CACHE (0.0ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT 1 [["id", 3]]CACHE (0.0ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT 1 [["id", 3]]CACHE (0.0ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT 1 [["id", 3]]… (around 100 calls)

By applying the memoization pattern, the cached query count was reduced from around 100 to less than 40

“Those cache calls mean Rails is returning the cached result of the SQL query, but it doesn’t include the cost of building the

User object.”

“And because Rails hides the cost of object creation these queries cost more than the

0.0ms and 0.1ms reported!”

http://gavinmiller.io/2013/basics-of-ruby-memoization/

THANK YOU!

questions?

top related