Skip to content

Instantly share code, notes, and snippets.

@mchung
Forked from jgaskins/benchmark.rb
Last active August 5, 2018 23:14
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 mchung/0662ec458f8ce874fb41b7525b94f38a to your computer and use it in GitHub Desktop.
Save mchung/0662ec458f8ce874fb41b7525b94f38a to your computer and use it in GitHub Desktop.
Hashie vs OpenStruct vs PORO performance
require 'hashie'
require 'ostruct'
require 'benchmark/ips'
class PORO
attr_reader :foo, :bar, :baz
def initialize attrs = {}
attrs.each do |attr, value|
instance_variable_set "@#{attr}", value
end
end
end
attrs = {foo: 1, bar: true, baz: 'quux'}
hashie = Hashie::Mash.new(attrs)
ostruct = OpenStruct.new(attrs)
poro = PORO.new(attrs)
Benchmark.ips do |x|
x.report 'Hashie alloc' do
Hashie::Mash.new(attrs)
end
x.report 'OpenStruct alloc' do
OpenStruct.new(attrs)
end
x.report 'PORO alloc' do
PORO.new(attrs)
end
x.compare!
end
Benchmark.ips do |x|
x.report 'Hashie access' do
hashie.foo
hashie.bar
hashie.baz
end
x.report 'OStruct access' do
ostruct.foo
ostruct.bar
ostruct.baz
end
x.report 'PORO access' do
poro.foo
poro.bar
poro.baz
end
x.compare!
end
# August 4th, 2018
# benchmark-ips (2.7.2)
# hashie (3.5.7)
# › ruby bm.rb
# Warming up --------------------------------------
# Hashie alloc 16.192k i/100ms
# OpenStruct alloc 80.273k i/100ms
# PORO alloc 68.089k i/100ms
# Calculating -------------------------------------
# Hashie alloc 160.567k (±15.3%) i/s - 777.216k in 5.041534s
# OpenStruct alloc 889.794k (±11.0%) i/s - 4.415M in 5.037222s
# PORO alloc 754.690k (± 8.5%) i/s - 3.745M in 5.003046s
# Comparison:
# OpenStruct alloc: 889793.9 i/s
# PORO alloc: 754690.4 i/s - same-ish: difference falls within error
# Hashie alloc: 160566.8 i/s - 5.54x slower
# Warming up --------------------------------------
# Hashie access 49.953k i/100ms
# OStruct access 199.954k i/100ms
# PORO access 322.592k i/100ms
# Calculating -------------------------------------
# Hashie access 565.606k (± 2.3%) i/s - 2.847M in 5.036913s
# OStruct access 3.661M (± 2.9%) i/s - 18.396M in 5.029748s
# PORO access 9.389M (± 2.3%) i/s - 47.098M in 5.019371s
# Comparison:
# PORO access: 9388639.8 i/s
# OStruct access: 3660851.4 i/s - 2.56x slower
# Hashie access: 565605.8 i/s - 16.60x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment