Created
June 2, 2010 04:27
-
-
Save leandro/421927 to your computer and use it in GitHub Desktop.
This file contains hidden or 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' | |
| class Hash | |
| def hash_from_1(*keys) | |
| keys.inject({}) { |memo, obj| memo.merge(obj => self[obj]) } | |
| end | |
| def hash_from_2(*keys) | |
| self.dup.delete_if { |k, v| !keys.include? k } | |
| end | |
| def hash_from_3(*keys) | |
| Hash[keys.zip(self.values_at(*keys))] | |
| end | |
| def hash_from_4(*keys) | |
| hash = {} | |
| for k in keys | |
| hash[k] = self[k] | |
| end | |
| hash | |
| end | |
| end | |
| Benchmark.bm(7) do |b| | |
| hash = {:foo => 1, :bar => 2, :foobar => 3} | |
| b.report('leandro :') { 100_000.times { hash.hash_from_1(:foo, :bar) } } | |
| b.report('cassio :') { 100_000.times { hash.hash_from_2(:foo, :bar) } } | |
| b.report('caio :') { 100_000.times { hash.hash_from_3(:foo, :bar) } } | |
| b.report('leandro-2:') { 100_000.times { hash.hash_from_4(:foo, :bar) } } | |
| end | |
| #@@@!leandro@mandigal:~!: ruby tmp/hash_from.rb | |
| # user system total real | |
| #leandro : 0.750000 0.000000 0.750000 ( 0.755851) | |
| #cassio : 0.500000 0.000000 0.500000 ( 0.503797) | |
| #caio : 0.320000 0.000000 0.320000 ( 0.316647) | |
| #leandro-2: 0.260000 0.000000 0.260000 ( 0.268218) | |
| #@@@!leandro@mandigal:~!: ruby tmp/hash_from.rb | |
| # user system total real | |
| #leandro : 0.750000 0.000000 0.750000 ( 0.750898) | |
| #cassio : 0.500000 0.000000 0.500000 ( 0.504918) | |
| #caio : 0.310000 0.000000 0.310000 ( 0.315486) | |
| #leandro-2: 0.270000 0.000000 0.270000 ( 0.268886) | |
| #@@@!leandro@mandigal:~!: ruby tmp/hash_from.rb | |
| # user system total real | |
| #leandro : 0.750000 0.000000 0.750000 ( 0.754943) | |
| #cassio : 0.500000 0.000000 0.500000 ( 0.505592) | |
| #caio : 0.310000 0.000000 0.310000 ( 0.314278) | |
| #leandro-2: 0.270000 0.010000 0.280000 ( 0.272884) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment