Created
April 5, 2011 22:01
-
-
Save wtn/904677 to your computer and use it in GitHub Desktop.
compare Array#inject({}) to Array#map and Hash[]
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
ATTRIBUTES = %w{aa bb cc dd ee ff gg} | |
ITERATION_COUNT = 100_000 | |
DELTA_CHAR = "\u0394" | |
def self.hash_inject_time_elapsed | |
start_time = Time.now | |
ITERATION_COUNT.times do | |
ATTRIBUTES.inject({}) {|h,s| h[s] = s.length; h } | |
end | |
Time.now - start_time | |
end | |
def self.map_and_hash_time_elapsed | |
start_time = Time.now | |
ITERATION_COUNT.times do | |
Hash[ ATTRIBUTES.map {|s| [s, s.length] } ] | |
end | |
Time.now - start_time | |
end | |
def self.report_savings | |
inject_time = hash_inject_time_elapsed | |
map_time = map_and_hash_time_elapsed | |
time_difference = inject_time - map_time | |
savings_ratio = time_difference.to_f / inject_time | |
"#{DELTA_CHAR} #{"%.2f" % (savings_ratio * 100)}%" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment