Skip to content

Instantly share code, notes, and snippets.

@mahm mahm/ruby_vs_mongo.rb
Last active Aug 29, 2015

Embed
What would you like to do?
Ruby vs MongoDB
require 'benchmark'
require 'mongo'
def generate_parts(size)
area_patterns = [['main'], ['sub'], ['header', 'footer']]
enable_patterns = [true, false]
level_patterns = ['/level1', '/level1/level2', '/level1/level2/level3']
(1..size).map do |n|
{
name: "part_#{n}",
enable: enable_patterns.sample,
area: area_patterns.sample,
level: level_patterns.sample([*1..3].sample)
}
end
end
def setup_mongo(parts)
c = Mongo::MongoClient.new
c.drop_database('parts_benchmark')
db = c.db('parts_benchmark')
coll = db.collection('parts')
parts.each{|part| coll.insert(part) }
coll
end
def benchmark(size)
puts "** #{size}個のデータから100回検索"
parts = generate_parts(size)
collection = setup_mongo(parts)
Benchmark.bm(10) do |b|
b.report('ruby_hash') { 100.times { ruby_hash(parts) } }
b.report('mongodb') { 100.times { mongodb(collection) } }
end
puts ''
end
def ruby_hash(parts)
parts.select do |part|
part[:enable] == true && part[:level].include?('/level1/level2') && part[:area].include?('main')
end
end
def mongodb(collection)
collection.find({
enable: true,
level: {'$in' => ['/level1/level2']},
area: {'$in' => ['main']}
}).to_a
end
[1000, 10000, 100000].each do |parts_size|
benchmark(parts_size)
end
** 1000個のデータから100回検索
user system total real
ruby_hash 0.030000 0.000000 0.030000 ( 0.029065)
mongodb 0.330000 0.110000 0.440000 ( 0.554554)
** 10000個のデータから100回検索
user system total real
ruby_hash 0.300000 0.000000 0.300000 ( 0.299092)
mongodb 2.930000 0.880000 3.810000 ( 4.753551)
** 100000個のデータから100回検索
user system total real
ruby_hash 3.710000 0.010000 3.720000 ( 3.713248)
mongodb 27.680000 8.560000 36.240000 ( 44.791536)
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.