Sha256: 10b8dcfa3b38c489c407ea10c8964b6836a705a8616bc47fe79019f1dbc27ef7

Contents?: true

Size: 948 Bytes

Versions: 13

Compression:

Stored size: 948 Bytes

Contents

# frozen_string_literal: true

require 'benchmark/ips'
require 'ostruct'

# This benchmark compares accessing an instance variable vs accessing a struct member (via a function). The actual method dispatch is about 25% slower.

puts "Ruby #{RUBY_VERSION} at #{Time.now}"

NAME = "Test Name"
EMAIL = "test@example.org"

test = nil

class ObjectHash
	def []= key, value
		instance_variable_set(key, value)
	end
	
	def [] key
		instance_variable_get(key)
	end
end

# There IS a measuarble difference:
Benchmark.ips do |x|
	x.report("Hash") do |i|
		i.times do
			p = {name: NAME, email: EMAIL}
			
			test = p[:name] + p[:email]
		end
	end
	
	x.report("OpenStruct") do |i|
		i.times do
			p = OpenStruct.new(name: NAME, email: EMAIL)
			
			test = p.name + p.email
	 end
	end
	
	x.report("ObjectHash") do |i|
		i.times do
			o = ObjectHash.new
			o[:@name] = NAME
			o[:@email] = EMAIL
			
			test = o[:@name] + o[:@email]
		end
	end
	
	x.compare!
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
utopia-2.15.1 benchmark/hash_vs_openstruct.rb
utopia-2.15.0 benchmark/hash_vs_openstruct.rb
utopia-2.14.0 benchmark/hash_vs_openstruct.rb
utopia-2.13.4 benchmark/hash_vs_openstruct.rb
utopia-2.13.3 benchmark/hash_vs_openstruct.rb
utopia-2.13.2 benchmark/hash_vs_openstruct.rb
utopia-2.13.1 benchmark/hash_vs_openstruct.rb
utopia-2.13.0 benchmark/hash_vs_openstruct.rb
utopia-2.12.4 benchmarks/hash_vs_openstruct.rb
utopia-2.12.3 benchmarks/hash_vs_openstruct.rb
utopia-2.12.2 benchmarks/hash_vs_openstruct.rb
utopia-2.12.1 benchmarks/hash_vs_openstruct.rb
utopia-2.12.0 benchmarks/hash_vs_openstruct.rb