Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails ActiveRecord SQL Caching vs Cache to Hash catalog benchmark
class DBBencmark
require 'benchmark'
@@n = 10000
@@test_langs = ['en', 'et']
def self.with_cache
catalog = {
langs: Language.all.index_by(&:code),
topics: Topic.all.index_by(&:name)
}
@@n.times.each do
{
topic_id: catalog[:topics][''].id,
lang1_id: catalog[:langs][@@test_langs.sample(1).first].id,
lang2_id: catalog[:langs][@@test_langs.sample(1).first].id
}
end
end
def self.without_cache
@@n.times.each do
{
topic_id: Topic.where(name: '').first.id,
lang1_id: Language.find_by(code: @@test_langs.sample(1).first).id,
lang2_id: Language.find_by(code: @@test_langs.sample(1).first).id
}
end
end
def self.perform
Benchmark.bmbm do |x|
x.report('cache') { with_cache }
x.report('no cache') { without_cache }
end
end
end

Results

Caching with ruby hash is about 1000 times faster than per iteration request to DB without Rails ActiveRecord SQL caching and about 200 times faster than per iteration request with SQL caching.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.