Instantly share code, notes, and snippets.

# schneems/gist:698df49c8c22cfea1d2c

Created October 29, 2014 20:49
Show Gist options
• Save schneems/698df49c8c22cfea1d2c to your computer and use it in GitHub Desktop.
Ruby 2.2.0 string allocation microbenchmarks

Accessing a hash

require 'benchmark/ips'

FOO  = "foo".freeze
HASH = {"foo" => "bar"}
Benchmark.ips do |x|
x.report("constant") { HASH[FOO] }
x.report("regular")  { HASH["foo"]}
end
Calculating -------------------------------------
constant    135268 i/100ms
regular    137251 i/100ms
-------------------------------------------------
constant  7206749.3 (±8.2%) i/s -   35710752 in   5.004233s
regular  7419691.3 (±5.3%) i/s -   37057770 in   5.012517s

Making a hash

FOO = "foo".freeze

Benchmark.ips do |x|
x.report("constant") { {FOO   => "bar"} }
x.report("regular")  { {"foo" => "bar"} }
end
Calculating -------------------------------------
constant     76658 i/100ms
regular     76115 i/100ms
-------------------------------------------------
constant  1471749.7 (±6.6%) i/s -    7359168 in   5.022988s
regular  1481781.7 (±8.4%) i/s -    7383155 in   5.025590s

Comparisons

Benchmark.ips do |x|
x.report("constant") { "foo" == FOO }
x.report("regular")  { "foo" == "foo" }
end
Calculating -------------------------------------
constant    127492 i/100ms
regular    114859 i/100ms
-------------------------------------------------
constant  5133411.2 (±8.3%) i/s -   25498400 in   5.016453s
regular  3790896.8 (±6.2%) i/s -   18951735 in   5.022476s

Passing in an argument to a regular method

Benchmark.ips do |x|
x.report("constant") { "foo".gsub(FOO, "") }
x.report("regular")  { "foo".gsub("foo", "") }
end
Calculating -------------------------------------
constant     56834 i/100ms
regular     57225 i/100ms
-------------------------------------------------
constant  1000248.1 (±6.8%) i/s -    5001392 in   5.026468s
regular   953884.1 (±6.5%) i/s -    4749675 in   5.005343s