Skip to content

Instantly share code, notes, and snippets.

@headius
Forked from ColinDKelley/hash_benchmark.rb
Last active January 1, 2016 16:29
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 headius/8170996 to your computer and use it in GitHub Desktop.
Save headius/8170996 to your computer and use it in GitHub Desktop.
require 'benchmark'
class Request
def initialize(first, last, city, state, country)
@hash =
{
'first'.freeze => first,
'last'.freeze => last,
'city'.freeze => city,
'state'.freeze => state,
'country'.freeze => country
}
end
def first
@hash['first'.freeze]
end
def last
@hash['last'.freeze]
end
def city
@hash['city'.freeze]
end
def state
@hash['state'.freeze]
end
def country
@hash['country'.freeze]
end
def to_a
[first, last, city, state, country]
end
end
result = Benchmark.measure do
request = Request.new('Colin', 'Kelley', 'Santa Barbara', 'CA', 'USA')
10_000_000.times do
request.to_a
end
end
puts result
Without magic comment: 14.61 seconds
With magic comment: 9.2 seconds # -*- immutable: string -*-
Immutable string version runs 1.58X faster (runs in just 63% of the time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment