Skip to content

Instantly share code, notes, and snippets.

@rud
Created February 2, 2018 10:11
Show Gist options
  • Save rud/b5839a264d4ee83525e5c9c7b796f66f to your computer and use it in GitHub Desktop.
Save rud/b5839a264d4ee83525e5c9c7b796f66f to your computer and use it in GitHub Desktop.
OpenStruct performance in ruby 2.4.
# Code from http://www.chrisrolle.com/en/blog/struct-vs-openstruct-benchmark
# gem install benchmark-ips
require 'benchmark/ips'
require 'ostruct'
class GCSuite
def warming(*)
run_gc
end
def running(*)
run_gc
end
def warmup_stats(*); end
def add_report(*); end
private
def run_gc
GC.enable
GC.start
GC.disable
end
end
suite = GCSuite.new
GeoStruct = Struct.new(:latitude, :longitude)
class GeoClass
attr_accessor :latitude, :longitude
def initialize(latitude:, longitude:)
@latitude = latitude
@longitude = longitude
end
end
Benchmark.ips do |bm|
bm.config(suite: suite)
bm.report('GeoStruct.new') do
GeoStruct.new(53.6, 11.4)
end
bm.report('Hash {}') do
{ latitude: 53.6, longitude: 11.4 }
end
bm.report('GeoClass.new') do
GeoClass.new(latitude: 53.6, longitude: 11.4)
end
bm.report('OpenStruct.new') do
OpenStruct.new(latitude: 53.6, longitude: 11.4)
end
end
$ ruby --version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin17]
$ ruby openstruct_benchmark.rb
Warming up --------------------------------------
GeoStruct.new 203.737k i/100ms
Hash {} 130.395k i/100ms
GeoClass.new 49.455k i/100ms
OpenStruct.new 61.689k i/100ms
Calculating -------------------------------------
GeoStruct.new 3.569M (±21.7%) i/s - 16.503M in 5.046587s
Hash {} 1.953M (±15.4%) i/s - 9.649M in 5.084186s
GeoClass.new 808.680k (±33.9%) i/s - 3.610M in 5.132875s
OpenStruct.new 708.399k (±32.8%) i/s - 3.146M in 5.087367s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment