Skip to content

Instantly share code, notes, and snippets.

@sdeming
Created June 5, 2018 02:38
Show Gist options
  • Save sdeming/da51e429a509f11562dc77c72b1e9051 to your computer and use it in GitHub Desktop.
Save sdeming/da51e429a509f11562dc77c72b1e9051 to your computer and use it in GitHub Desktop.
Quick simple benchmark between bsearch_index and index with over sorted list of numbers. Binary search is obvious winner. This is just the proof.
require 'benchmark'
ordered_array = (0..10_000).map { |p| [p,p,p,p,p] }.flatten
random_array = ordered_array.dup.shuffle
Benchmark.bm do |b|
b.report('index') do
random_array.map { |n| ordered_array.index(n) }
end
b.report('bsearch_index') do
random_array.map { |n| ordered_array.bsearch_index { |x| n <= x } }
end
end
#
# user system total real
# index 6.281000 0.000000 6.281000 ( 6.982050)
# bsearch_index 0.063000 0.000000 0.063000 ( 0.058774)
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment