Friday, January 19, 2018

Ruby - Array#bsearch

Array bsearch it's very handy and one of the fastest way to find a value from the array.

Let's do benchmark analysis, based on the result, bsearch more powerful than using array find method. 
require 'benchmark'

array_data = (0..100_000_000)

Benchmark.bm do |x|
x.report(:find) { array_data.find {|number| number > 50_000_000 } }
x.report(:bsearch) { array_data.bsearch {|number| number > 50_000_000 } }
end

user system total real
find 3.160000 0.000000 3.160000 ( 3.174570)
bsearch 0.000000 0.000000 0.000000 ( 0.000011)

It can find a match with only O(log n) complexity. 

No comments:

Post a Comment