Skip to content

Instantly share code, notes, and snippets.

@findchris
Created June 30, 2018 00:03
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 findchris/d9de438a3c7b7f0aae25dd0b22b5bbf0 to your computer and use it in GitHub Desktop.
Save findchris/d9de438a3c7b7f0aae25dd0b22b5bbf0 to your computer and use it in GitHub Desktop.
Class vs struct vs hash vs openstruct instantiation performance
require 'benchmark'
require 'ostruct'
REP = 1000000
User = Struct.new(:name, :age)
class Obj
def initialize(name, age)
@name = name
@age = age
end
end
USER = "User".freeze
AGE = 21
HASH = {:name => USER, :age => AGE}.freeze
Benchmark.bm 20 do |x|
x.report 'Class slow' do
REP.times do |index|
Obj.new("User", 21)
end
end
x.report 'Class fast' do
REP.times do |index|
Obj.new(USER, AGE)
end
end
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 '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
x.report 'Hash slow' do
REP.times do |index|
{:name => 'User', :age => 21}
end
end
x.report 'Hash fast' do
REP.times do |index|
{:name => USER, :age => AGE}
end
end
end
@findchris
Copy link
Author

Results:

                           user     system      total        real
Class slow             0.310000   0.000000   0.310000 (  0.317348)
Class fast             0.230000   0.000000   0.230000 (  0.233508)
OpenStruct slow       11.740000   0.290000  12.030000 ( 13.258977)
OpenStruct fast       10.780000   0.240000  11.020000 ( 12.225826)
Struct slow            0.290000   0.000000   0.290000 (  0.296622)
Struct fast            0.220000   0.000000   0.220000 (  0.219298)
Hash slow              0.610000   0.030000   0.640000 (  0.717739)
Hash fast              0.530000   0.030000   0.560000 (  0.609345)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment