Skip to content

Instantly share code, notes, and snippets.

@maletor
Forked from taq/enum_perf_small.rb
Last active June 7, 2018 23:08
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 maletor/2b6de3c64e94e8161842c09fdc22ebd3 to your computer and use it in GitHub Desktop.
Save maletor/2b6de3c64e94e8161842c09fdc22ebd3 to your computer and use it in GitHub Desktop.
Ruby 2.0 lazy enumerators small collection performance
require "benchmark"
include Benchmark
values = (0..10_000_000).to_a
bm(1_000_000) do |bench|
bench.report("map and select") do
values.map { |x| x * 3 }.select { |x| x % 4 == 0 }
end
bench.report("inject") do
values.inject([]) do |arr, x|
y = x * 3
arr << y if y % 4 == 0
arr
end
end
bench.report("each with object") do
values.each_with_object([]) do |x, arr|
y = x * 3
arr << y if y % 4 == 0
end
end
end
@jacknoble
Copy link

jacknoble commented Jun 7, 2018

include Benchmark

values = (0..10000).to_a

bm(100) do |bench|
  bench.report("inject") do
      values.reduce([]) do |arr, x|
         y = x * 10
         arr << y if x % 2 == 0
         arr
      end
   end
   bench.report("map and select") do
      values.map { |x| x * 10 }.select { |x| x % 2 == 0 } 
   end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment