Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created December 30, 2014 17:38
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 jodosha/8ca2bee6137be94e9dcb to your computer and use it in GitHub Desktop.
Save jodosha/8ca2bee6137be94e9dcb to your computer and use it in GitHub Desktop.
Ruby Hash#each vs #keys.each vs #each_key
#!/usr/bin/env ruby
require 'benchmark/ips'
STRING_HASH = Hash['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]
SYMBOL_HASH = Hash[a: 1, b: 2, c: 3, d: 4, e: 5]
Benchmark.ips do |x|
x.report('string each') { STRING_HASH.each {|k,_| } }
x.report('string keys') { STRING_HASH.keys.each {|k| } }
x.report('string each_key') { STRING_HASH.each_key {|k| } }
x.report('symbol each') { SYMBOL_HASH.each {|k,_| } }
x.report('symbol keys') { SYMBOL_HASH.keys.each {|k| } }
x.report('symbol each_key') { SYMBOL_HASH.each_key {|k| } }
end
__END__
Output:
Calculating -------------------------------------
string each 78.009k i/100ms
string keys 69.856k i/100ms
string each_key 81.488k i/100ms
symbol each 77.053k i/100ms
symbol keys 69.434k i/100ms
symbol each_key 81.968k i/100ms
-------------------------------------------------
string each 1.820M (± 5.9%) i/s - 9.127M
string keys 1.501M (±20.0%) i/s - 7.195M
string each_key 2.032M (± 5.1%) i/s - 10.186M
symbol each 1.834M (± 4.8%) i/s - 9.169M
symbol keys 1.492M (±20.4%) i/s - 7.152M
symbol each_key 2.021M (± 7.6%) i/s - 10.082M
Ruby:
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin13]
Hardware:
Hardware Overview:
Model Name: MacBook Air
Model Identifier: MacBookAir5,2
Processor Name: Intel Core i7
Processor Speed: 2 GHz
Number of Processors: 1
Total Number of Cores: 2
L2 Cache (per Core): 256 KB
L3 Cache: 4 MB
Memory: 8 GB
Boot ROM Version: MBA51.00EF.B02
SMC Version (system): 2.5f9
Software:
System Software Overview:
System Version: OS X 10.9.5 (13F34)
Kernel Version: Darwin 13.4.0
Time since boot: 15 days 1:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment