Skip to content

Instantly share code, notes, and snippets.

@yorickpeterse
Created March 3, 2015 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yorickpeterse/da524a182febcd130436 to your computer and use it in GitHub Desktop.
Save yorickpeterse/da524a182febcd130436 to your computer and use it in GitHub Desktop.
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