Created
March 3, 2015 10:00
-
-
Save yorickpeterse/da524a182febcd130436 to your computer and use it in GitHub Desktop.
This file contains 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/ips' | |
module Enumerable | |
def each_cons(num) | |
n = Rubinius::Type.coerce_to_collection_index num | |
raise ArgumentError, "invalid size: #{n}" if n <= 0 | |
return to_enum(:each_cons, num) { | |
if (enum_size = enumerator_size).nil? | |
nil | |
elsif enum_size == 0 | |
0 | |
else | |
enum_size - n + 1 | |
end | |
} unless block_given? | |
array = [] | |
each do | |
element = Rubinius.single_block_arg | |
array << element | |
array.shift if array.size > n | |
yield array.dup if array.size == n | |
end | |
nil | |
end | |
def each_cons_no_cache(num) | |
n = Rubinius::Type.coerce_to_collection_index num | |
raise ArgumentError, "invalid size: #{n}" if n <= 0 | |
return to_enum(:each_cons_no_cache, num) { | |
if enumerator_size.nil? | |
nil | |
elsif enumerator_size == 0 | |
0 | |
else | |
enumerator_size - n + 1 | |
end | |
} unless block_given? | |
array = [] | |
each do | |
element = Rubinius.single_block_arg | |
array << element | |
array.shift if array.size > n | |
yield array.dup if array.size == n | |
end | |
nil | |
end | |
end | |
numbers = 1..100 | |
Benchmark.ips do |bench| | |
bench.report '#each_cons' do | |
numbers.each_cons(4).size | |
end | |
bench.report '#each_cons_no_cache' do | |
numbers.each_cons(4).size | |
end | |
bench.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment