Created
June 6, 2024 14:31
-
-
Save ahx/668f2bb4fadcbf0a0e78abe7030a7917 to your computer and use it in GitHub Desktop.
Comparing performance of Data vs Hash in Ruby
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
# frozen_string_literal: true | |
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'benchmark-ips' | |
gem 'benchmark-memory' | |
end | |
require 'benchmark/ips' | |
require 'benchmark/memory' | |
D = Data.define(:name, :id) | |
Benchmark.ips do |x| | |
x.report('Data') do | |
v = D.new(name: 'Quentin', id: '23') | |
v.name + v.id | |
end | |
x.report('Hash') do | |
v = { name: 'Quentin', id: '23' } | |
v[:name] + v[:id] | |
end | |
x.compare! | |
end | |
Benchmark.memory do |x| | |
x.report('Data') do | |
v = D.new(name: 'Quentin', id: '23') | |
v.name + v.id | |
end | |
x.report('Hash') do | |
v = { name: 'Quentin', id: '23' } | |
v[:name] + v[:id] | |
end | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ruby 3.3.1 (2024-04-23 revision c56cd86388) [arm64-darwin23]
Warming up --------------------------------------
Data 249.750k i/100ms
Hash 485.145k i/100ms
Calculating -------------------------------------
Data 2.545M (± 5.9%) i/s - 12.987M in 5.122244s
Hash 4.860M (±10.7%) i/s - 24.257M in 5.075486s
Comparison:
Hash: 4859651.6 i/s
Data: 2545455.0 i/s - 1.91x slower
Calculating -------------------------------------
Data 240.000 memsize ( 0.000 retained)
3.000 objects ( 0.000 retained)
1.000 strings ( 0.000 retained)
Hash 200.000 memsize ( 0.000 retained)
2.000 objects ( 0.000 retained)
1.000 strings ( 0.000 retained)
Comparison:
Hash: 200 allocated
Data: 240 allocated - 1.20x more