Skip to content

Instantly share code, notes, and snippets.

@palexander
Last active January 4, 2016 07:59
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 palexander/8592640 to your computer and use it in GitHub Desktop.
Save palexander/8592640 to your computer and use it in GitHub Desktop.
Benchmark to compare hash and keyword arguments in method invocations
require 'benchmark'
COUNT = 10_000_000
NAME = "Test Name"
EMAIL = "test@example.org"
class Person
attr_accessor :name, :email
def set_with_hash(options = {})
@name = options[:name] || "default name"
@email = options[:email] || "default@example.org"
end
def set_with_keywords(name: "default name", email: "default@example.org")
@name = name
@email = email
end
end
Benchmark.bm(10) do |x|
x.report("hash:") do
COUNT.times do
p = Person.new
p.set_with_hash(name: NAME, email: EMAIL)
end
end
x.report("keywords:") do
COUNT.times do
p = Person.new
p.set_with_keywords(name: NAME, email: EMAIL)
end
end
end
user system total real
hash: 8.130000 0.290000 8.420000 ( 8.420061)
keywords: 13.720000 0.540000 14.260000 ( 14.275596)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment