Skip to content

Instantly share code, notes, and snippets.

@ololobus
Last active March 11, 2023 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ololobus/785f1005da29850d6a85 to your computer and use it in GitHub Desktop.
Save ololobus/785f1005da29850d6a85 to your computer and use it in GitHub Desktop.
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.

@studyworm
Copy link

Excellent!!!
I want to know this result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment