Skip to content

Instantly share code, notes, and snippets.

@wtn
Created April 5, 2011 22:01
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 wtn/904677 to your computer and use it in GitHub Desktop.
Save wtn/904677 to your computer and use it in GitHub Desktop.
compare Array#inject({}) to Array#map and Hash[]
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