Sha256: f1f33eda8c6a6ce56fc96d91466216464bb9e81f0bfdebbf1e2538308b50f8a6

Contents?: true

Size: 917 Bytes

Versions: 60

Compression:

Stored size: 917 Bytes

Contents

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

60 entries across 60 versions & 1 rubygems

Version Path
utopia-2.11.1 benchmarks/hash_vs_openstruct.rb
utopia-2.11.0 benchmarks/hash_vs_openstruct.rb
utopia-2.10.0 benchmarks/hash_vs_openstruct.rb
utopia-2.9.5 benchmarks/hash_vs_openstruct.rb
utopia-2.9.3 benchmarks/hash_vs_openstruct.rb
utopia-2.9.2 benchmarks/hash_vs_openstruct.rb
utopia-2.9.1 benchmarks/hash_vs_openstruct.rb
utopia-2.9.0 benchmarks/hash_vs_openstruct.rb
utopia-2.8.2 benchmarks/hash_vs_openstruct.rb
utopia-2.8.1 benchmarks/hash_vs_openstruct.rb
utopia-2.8.0 benchmarks/hash_vs_openstruct.rb
utopia-2.7.0 benchmarks/hash_vs_openstruct.rb
utopia-2.6.0 benchmarks/hash_vs_openstruct.rb
utopia-2.5.5 benchmarks/hash_vs_openstruct.rb
utopia-2.5.4 benchmarks/hash_vs_openstruct.rb
utopia-2.5.3 benchmarks/hash_vs_openstruct.rb
utopia-2.5.1 benchmarks/hash_vs_openstruct.rb
utopia-2.5.0 benchmarks/hash_vs_openstruct.rb
utopia-2.4.1 benchmarks/hash_vs_openstruct.rb
utopia-2.4.0 benchmarks/hash_vs_openstruct.rb