Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OpenStruct Benchmark
require 'benchmark'
require 'ostruct'
require 'hashie'
REP = 100000
mash = Hashie::Mash.new
User = Struct.new(:name, :age)
USER = "User".freeze
AGE = 21
HASH = {name: USER, age: AGE}.freeze
Benchmark.bm 20 do |x|
x.report 'OpenStruct slow' do
REP.times do |index|
OpenStruct.new(name: "User", age: 21)
end
end
x.report 'OpenStruct fast' do
REP.times do |index|
OpenStruct.new(HASH)
end
end
x.report 'OpenStruct assign' do
REP.times do |index|
t = OpenStruct.new
t.name = "User"
t.age = 21
end
end
x.report "Hashie slow" do
REP.times do |index|
Hashie::Mash.new(name: "User", age: 21)
end
end
x.report "Hashie fast" do
REP.times do |index|
Hashie::Mash.new(HASH)
end
end
x.report "Hashie assign" do
REP.times do |index|
t = Hashie::Mash.new
t.name = "User"
t.age = 21
end
end
x.report 'Struct slow' do
REP.times do |index|
User.new("User", 21)
end
end
x.report 'Struct fast' do
REP.times do |index|
User.new(USER, AGE)
end
end
end
user system total real
OpenStruct slow 1.320000 0.030000 1.350000 ( 1.371876)
OpenStruct fast 1.270000 0.030000 1.300000 ( 1.355350)
OpenStruct assign 1.370000 0.020000 1.390000 ( 1.402749)
Hashi assign 0.800000 0.000000 0.800000 ( 0.816760)
Hashi slow 0.420000 0.010000 0.430000 ( 0.415394)
Hashi fast 0.320000 0.000000 0.320000 ( 0.323032)
Struct slow 0.030000 0.000000 0.030000 ( 0.038274)
Struct fast 0.030000 0.000000 0.030000 ( 0.026585)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.