Skip to content

Instantly share code, notes, and snippets.

@tcaddy
Last active October 12, 2017 19:52
Show Gist options
  • Save tcaddy/12a0f7ad02286f1a17b6366242e894f1 to your computer and use it in GitHub Desktop.
Save tcaddy/12a0f7ad02286f1a17b6366242e894f1 to your computer and use it in GitHub Desktop.
Benchmark String#freeze
#!/usr/bin/env ruby
# Based on http://blog.honeybadger.io/when-to-use-freeze-and-frozen-in-ruby/#reducing-object-allocations
# but for Ruby 1.9.3
require 'benchmark'
class FreezeBenchmark
NORMAL = 'NORMAL'
FROZEN = 'FROZEN'.freeze
def self.init(n = 100000)
Benchmark.bm do |x|
x.report("normal") { n.times { get_string(false) } }
x.report("frozen") { n.times { get_string(true) } }
end
end
private
def self.get_string(use_frozen)
return use_frozen ? FROZEN : NORMAL
end
end
FreezeBenchmark.init
# Results with MRI 1.9.3p551:
# user system total real
# normal 0.010000 0.000000 0.010000 ( 0.012295)
# frozen 0.010000 0.000000 0.010000 ( 0.009562)
# Results with MRI 2.2.7p470:
# user system total real
# normal 0.010000 0.000000 0.010000 ( 0.007917)
# frozen 0.010000 0.000000 0.010000 ( 0.007820)
# Results with MRI 2.4.1p111:
# user system total real
# normal 0.010000 0.000000 0.010000 ( 0.007662)
# frozen 0.010000 0.000000 0.010000 ( 0.006562)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment