Skip to content

Instantly share code, notes, and snippets.

@mahm
Last active August 29, 2015 14:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mahm/0aa0cce28830ce638eb6 to your computer and use it in GitHub Desktop.
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