Created
March 11, 2013 16:07
-
-
Save pcarrier/5135339 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'benchmark' | |
| short_array = [1, 2, 3, 4, 1, 2, 5, 6] | |
| long_array = ([1] * 1000) + short_array | |
| short_match = [1, 2, 5] | |
| long_match = short_match * 10 | |
| class Array | |
| def find_sub_1(match) | |
| (each_cons(match.size).with_index.find {|x, i| x == match } || []).last | |
| end | |
| def find_sub_2(match) | |
| (size - match.size).times.find do |i| | |
| match.each_with_index.all? {|e, j| self[i + j] == e } | |
| end | |
| end | |
| def find_sub_3 match | |
| 0.upto(self.length-match.length) do |i| | |
| catch :fail do | |
| 0.upto(match.length-1) do |j| | |
| throw :fail unless self[i+j] == match[j] | |
| end | |
| return i | |
| end | |
| end | |
| nil | |
| end | |
| end | |
| Benchmark.bmbm do |b| | |
| b.report('arrays') do | |
| 1000.times { long_array.find_sub_1(long_match) } | |
| end | |
| b.report('algorithm') do | |
| 1000.times { long_array.find_sub_2(long_match) } | |
| end | |
| b.report('pierre') do | |
| 1000.times { long_array.find_sub_3(long_match) } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment