Skip to content

Instantly share code, notes, and snippets.

@mahm mahm/normal_vs_lazy_1.rb

Last active Aug 29, 2015
Embed
What would you like to do?
normal select vs lazy select
require 'benchmark'
def normal_selector(array, word)
array.select{|hash| hash[:name].match "#{word}"}.to_a
end
def lazy_selector(array, word)
array.lazy.select{|hash| hash[:name].match "#{word}"}.to_a
end
def benchmark(array)
puts "** #{array.size}個のデータを100回検索"
Benchmark.bm(16) do |target|
target.report('normal_selector') { 100.times { normal_selector(array, '3') } }
target.report('lazy_selector') { 100.times { lazy_selector(array, '3') } }
end
end
def generate_array(size)
(1..size).map{|n| {name: "test#{n}", order: n}}
end
[100, 1000, 10000].each do |array_size|
benchmark(generate_array(array_size))
end
require 'benchmark'
def normal_selector(array, word)
array.select{|hash| hash[:name].match "#{word}"}.first(10)
end
def lazy_selector(array, word)
array.lazy.select{|hash| hash[:name].match "#{word}"}.first(10)
end
def benchmark(array)
puts "** #{array.size}個のデータを100回検索"
Benchmark.bm(16) do |target|
target.report('normal_selector') { 100.times { normal_selector(array, '3') } }
target.report('lazy_selector') { 100.times { lazy_selector(array, '3') } }
end
end
def generate_array(size)
(1..size).map{|n| {name: "test#{n}", order: n}}
end
[100, 1000, 10000].each do |array_size|
benchmark(generate_array(array_size))
end
** 100個のデータを100回検索
user system total real
normal_selector 0.040000 0.000000 0.040000 ( 0.040522)
lazy_selector 0.040000 0.000000 0.040000 ( 0.044772)
** 1000個のデータを100回検索
user system total real
normal_selector 0.390000 0.000000 0.390000 ( 0.392909)
lazy_selector 0.430000 0.000000 0.430000 ( 0.434679)
** 10000個のデータを100回検索
user system total real
normal_selector 4.210000 0.040000 4.250000 ( 4.248381)
lazy_selector 4.580000 0.010000 4.590000 ( 4.595210)
** 100個のデータを100回検索
user system total real
normal_selector 0.040000 0.000000 0.040000 ( 0.044624)
lazy_selector 0.020000 0.000000 0.020000 ( 0.017945)
** 1000個のデータを100回検索
user system total real
normal_selector 0.440000 0.000000 0.440000 ( 0.437309)
lazy_selector 0.020000 0.000000 0.020000 ( 0.019867)
** 10000個のデータを100回検索
user system total real
normal_selector 4.820000 0.040000 4.860000 ( 4.860706)
lazy_selector 0.020000 0.000000 0.020000 ( 0.023823)
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.