facets
facets copied to clipboard
Comparison of Enumerable#graph with to_h
Hi!
I compaired Enumerable#graph from facets with Enumerable.to_h from Ruby.
require 'facets'
require 'benchmark'
k = 10_000_000
numbers = (1..k)
Benchmark.bmbm do |x|
x.report(:graph) { numbers.graph { |n| [n, n*n] } }
x.report(:map) { numbers.map { |n| [n, n*n] }.to_h }
end
Rehearsal -----------------------------------------
graph 9.780000 0.150000 9.930000 ( 9.949591)
map 10.770000 0.160000 10.930000 ( 10.934696)
------------------------------- total: 20.860000sec
user system total real
graph 8.530000 0.000000 8.530000 ( 8.527301)
map 8.130000 0.000000 8.130000 ( 8.132008)
Results are comparable. Second version should have a bigger memory footprint, so I compared them too:
# graph.rb
require 'facets'
k = 10_000_000
numbers = (1..k)
numbers.graph { |n| [n, n*n] }
ruby-prof graph.rb
Measure Mode: memory
Total: 581817.523438
# to_h.rb
k = 10_000_000
numbers = (1..k)
numbers.map { |n| [n, n*n] }.to_h
ruby-prof to_h.rb
Measure Mode: memory
Total: 649572.859375
Yes, the memory footprint is larger as expected.
Implementations may give different results on a different input, so I started to explore them, and found, that this line: https://github.com/rubyworks/facets/blob/master/lib/core/facets/enumerable/graph.rb#L29 is not covered by tests. This might be an issue.