Created
June 30, 2018 00:03
-
-
Save findchris/d9de438a3c7b7f0aae25dd0b22b5bbf0 to your computer and use it in GitHub Desktop.
Class vs struct vs hash vs openstruct instantiation performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: