Skip to content

Instantly share code, notes, and snippets.

@pmahoney
Created December 31, 2012 17:59
Show Gist options
  • Save pmahoney/4421626 to your computer and use it in GitHub Desktop.
Save pmahoney/4421626 to your computer and use it in GitHub Desktop.
require 'benchmark'
A = 'a'
B = 'b'
C = 'c'
D = 'd'
E = 'e'
F = 'f'
G = 'g'
H = 'h'
I = 'i'
NOPE = 'nope'
def literal
{
A => rand,
B => rand,
C => rand,
D => rand,
E => rand,
F => rand,
G => rand,
H => rand,
I => rand
}
end
class Key < String
attr_reader :hash
def initialize(string)
super(string)
@hash = string.hash
freeze
end
end
def k(str)
Key.new(str)
end
KA = k('a')
KB = k('b')
KC = k('c')
KD = k('d')
KE = k('e')
KF = k('f')
KG = k('g')
KH = k('h')
KI = k('i')
KNOPE = k('nope')
def literal2
{
KA => rand,
KB => rand,
KC => rand,
KD => rand,
KE => rand,
KF => rand,
KG => rand,
KH => rand,
KI => rand
}
end
n = 500000
Benchmark.bmbm(7) do |x|
x.report("literal:") { n.times { h = literal; h[KF]; h[NOPE] } }
x.report("literal2:") { n.times { h = literal2; h[KF]; h[KNOPE] } }
end
jruby 1.7.1 (1.9.3p327) 2012-12-03 30a153b on Java HotSpot(TM) 64-Bit Server VM 1.6.0_35-b10-428-10M3811 [darwin-x86_64]
Rehearsal ---------------------------------------------
literal: 2.600000 0.060000 2.660000 ( 1.304000)
literal2: 1.380000 0.050000 1.430000 ( 0.745000)
------------------------------------ total: 4.090000sec
user system total real
literal: 0.740000 0.030000 0.770000 ( 0.740000)
literal2: 0.610000 0.020000 0.630000 ( 0.598000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment