Created
September 2, 2016 13:50
-
-
Save tristang/a961fdc327e7d79439729a6c381227dc to your computer and use it in GitHub Desktop.
OpenStruct vs Struct vs Hash 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) | |
| 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 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
| 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
I changed the code to use benchmark-ips so that it's easier to read. I've also moved around and order fast first before the slow one, then moved the hashes to the top to make it the reference point.
Here's the code:
Here's the result for Ruby 3.4.1 on arm64 Macbook M4 Max (plugged):