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.
Last active
March 11, 2023 00:25
-
-
Save ololobus/785f1005da29850d6a85 to your computer and use it in GitHub Desktop.
Rails ActiveRecord SQL Caching vs Cache to Hash catalog benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent!!!
I want to know this result.