Last active
August 10, 2016 10:50
Star
You must be signed in to star a gist
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' | |
def inject_method(arr) | |
arr.inject(Hash.new(0)) { |a, e| a[e] += 1 ; a } | |
end | |
def each_wo_method(arr) | |
arr.each_with_object(Hash.new(0)) { |e, a| a[e] += 1 } | |
end | |
def hash_method(arr) | |
Hash[arr.group_by{ |e| e }.map{ |k,v| [k,v.length] }] | |
end | |
@small_array = %w(how much wood would a wood chuck chuck) | |
@big_array = @small_array * 10000 | |
iterations = 200 | |
Benchmark.bmbm do |x| | |
x.report("small arr inject: ") { iterations.times { inject_method(@small_array) } } | |
x.report("small arr each_w_o:") { iterations.times { each_wo_method(@small_array) } } | |
x.report("small arr Hash: ") { iterations.times { hash_method(@small_array) } } | |
x.report("big arr inject: ") { iterations.times { inject_method(@big_array) } } | |
x.report("big arr each_w_o:") { iterations.times { each_wo_method(@big_array) } } | |
x.report("big arr Hash: ") { iterations.times { hash_method(@big_array) } } | |
end | |
=begin | |
Rehearsal ------------------------------------------------------- | |
small arr inject: 0.000000 0.000000 0.000000 ( 0.006483) | |
small arr each_w_o: 0.000000 0.000000 0.000000 ( 0.000821) | |
small arr Hash: 0.010000 0.000000 0.010000 ( 0.002315) | |
big arr inject: 3.260000 0.010000 3.270000 ( 3.267461) | |
big arr each_w_o: 3.190000 0.000000 3.190000 ( 3.204037) | |
big arr Hash: 2.210000 0.050000 2.260000 ( 2.262594) | |
---------------------------------------------- total: 8.730000sec | |
user system total real | |
small arr inject: 0.000000 0.000000 0.000000 ( 0.000473) | |
small arr each_w_o: 0.000000 0.000000 0.000000 ( 0.000466) | |
small arr Hash: 0.000000 0.000000 0.000000 ( 0.000747) | |
big arr inject: 3.290000 0.000000 3.290000 ( 3.302613) | |
big arr each_w_o: 3.160000 0.000000 3.160000 ( 3.174065) | |
big arr Hash: 2.150000 0.050000 2.200000 ( 2.206949) | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment