Skip to content

Instantly share code, notes, and snippets.

@ColinDKelley
Last active November 5, 2016 17:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ColinDKelley/8156708 to your computer and use it in GitHub Desktop.
Save ColinDKelley/8156708 to your computer and use it in GitHub Desktop.
hash benchmark
# -*- immutable: string -*-
require 'benchmark'
class Request
def initialize(first, last, city, state, country)
@hash =
{
'first' => first,
'last' => last,
'city' => city,
'state' => state,
'country' => country
}
end
def first
@hash['first']
end
def last
@hash['last']
end
def city
@hash['city']
end
def state
@hash['state']
end
def country
@hash['country']
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: 11.43 seconds
With magic comment: 6.98 seconds # -*- immutable: string -*-
Immutable string version runs 1.64X faster (runs in just 61% of the time) compared to stock Ruby 2.1.0
Github pull request:
https://github.com/ruby/ruby/pull/487
Ruby issue:
https://bugs.ruby-lang.org/issues/9278
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment