-
-
Save gildemberg-santos/52d490181bed161171ce71c0d7ffe3f0 to your computer and use it in GitHub Desktop.
OpenStruct vs Struct vs Hash performance
This file contains 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) | |
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 '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 |
This file contains 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
user system total real | |
OpenStruct slow 8.150000 0.000000 8.150000 ( 8.153797) | |
OpenStruct fast 7.980000 0.000000 7.980000 ( 7.983929) | |
Struct slow 0.270000 0.000000 0.270000 ( 0.268514) | |
Struct fast 0.200000 0.000000 0.200000 ( 0.196950) | |
Hash slow 0.580000 0.000000 0.580000 ( 0.584160) | |
Hash fast 0.460000 0.000000 0.460000 ( 0.458502) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment