Skip to content

Instantly share code, notes, and snippets.

@splattael splattael/bench.rb
Last active Dec 10, 2015

Embed
What would you like to do?
Compiling...
require "benchmark/ips"
HASH = { :foo => 1, :bar => 2 }
def hc
{
:foo => HASH.fetch(:foo),
:bar => HASH.fetch(:bar),
}
end
def dyn
HASH.each_with_object({}) do |(key, value), result|
result[key] = value
end
end
def compile!
content = HASH.map do |key, value|
"#{key.inspect} => HASH.fetch(#{key.inspect}),"
end.join(" ")
body = "def compiled; { #{content} }; end"
puts body
eval body
end
compile!
p compiled
p dyn
p hc
Benchmark.ips do |x|
x.report "hash" do
dyn
end
x.report "hc" do
hc
end
x.report "compiled" do
compiled
end
x.compare!
end
def compiled; { :foo => HASH.fetch(:foo), :bar => HASH.fetch(:bar), }; end
{:foo=>1, :bar=>2}
{:foo=>1, :bar=>2}
{:foo=>1, :bar=>2}
Calculating -------------------------------------
hash 28.130k i/100ms
hc 45.333k i/100ms
compiled 46.710k i/100ms
-------------------------------------------------
hash 423.640k (± 6.0%) i/s - 2.110M
hc 869.989k (± 5.9%) i/s - 4.352M
compiled 915.810k (± 5.5%) i/s - 4.578M
Comparison:
compiled: 915810.3 i/s
hc: 869988.7 i/s - 1.05x slower
hash: 423640.1 i/s - 2.16x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.