Skip to content

Instantly share code, notes, and snippets.

@olivernn
Last active December 20, 2015 11:09
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 olivernn/6121312 to your computer and use it in GitHub Desktop.
Save olivernn/6121312 to your computer and use it in GitHub Desktop.
Benchmarking map and compact vs each_with_object vs inject
require 'benchmark'
words = File.open('/usr/share/dict/words', 'r') do |file|
file.each_line.take(100_000).map(&:chomp)
end
Benchmark.bmbm(20) do |x|
GC.start
x.report("map") do
words.map do |word|
word if word.size > 5
end
.compact
end
GC.start
x.report("each_with_object") do
words.each_with_object([]) do |word, long_words|
long_words << word if word.size > 5
end
end
GC.start
x.report("inject") do
words.inject([]) do |memo, word|
memo << word if word.size > 5
memo
end
end
GC.start
x.report("select") do
words.select do |word|
word.size > 5
end
end
end
Rehearsal --------------------------------------------------------
map 0.010000 0.000000 0.010000 ( 0.014050)
each_with_object 0.020000 0.000000 0.020000 ( 0.020350)
inject 0.020000 0.000000 0.020000 ( 0.017213)
select 0.010000 0.000000 0.010000 ( 0.018353)
----------------------------------------------- total: 0.060000sec
user system total real
map 0.010000 0.000000 0.010000 ( 0.011882)
each_with_object 0.010000 0.010000 0.020000 ( 0.017177)
inject 0.020000 0.000000 0.020000 ( 0.017326)
select 0.010000 0.000000 0.010000 ( 0.011077)
Rehearsal --------------------------------------------------------
map 0.010000 0.000000 0.010000 ( 0.012690)
each_with_object 0.020000 0.010000 0.030000 ( 0.016924)
inject 0.010000 0.000000 0.010000 ( 0.018579)
select 0.020000 0.000000 0.020000 ( 0.018294)
----------------------------------------------- total: 0.070000sec
user system total real
map 0.010000 0.000000 0.010000 ( 0.011580)
each_with_object 0.010000 0.000000 0.010000 ( 0.016984)
inject 0.010000 0.000000 0.010000 ( 0.018552)
select 0.010000 0.000000 0.010000 ( 0.011182)
Rehearsal --------------------------------------------------------
map 0.010000 0.000000 0.010000 ( 0.012689)
each_with_object 0.010000 0.000000 0.010000 ( 0.016983)
inject 0.020000 0.010000 0.030000 ( 0.018153)
select 0.020000 0.000000 0.020000 ( 0.018138)
----------------------------------------------- total: 0.070000sec
user system total real
map 0.010000 0.000000 0.010000 ( 0.011877)
each_with_object 0.020000 0.000000 0.020000 ( 0.016739)
inject 0.020000 0.000000 0.020000 ( 0.018349)
select 0.010000 0.000000 0.010000 ( 0.011309)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment