Sha256: 49666661920e1b0a9346aacc2a00e1ae6dee7ac9722964f40cf0fae822d106d8

Contents?: true

Size: 1.35 KB

Versions: 60

Compression:

Stored size: 1.35 KB

Contents

require 'benchmark/ips'

# 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}"

ItemsStruct = Struct.new(:items) do
	def initialize
		super []
	end
	
	def push_me_pull_you(value = :x)
		items = self.items
		
		items << value
		items.pop
	end
	
	def empty?
		self.items.empty?
	end
end

class ItemsClass
	def initialize
		@items = []
	end
	
	def push_me_pull_you(value = :x)
		items = @items
		
		items << value
		items.pop
	end
	
	def empty?
		@items.empty?
	end
end

# There IS a measuarble difference:
Benchmark.ips do |x|
	x.report("Struct#empty?") do |times|
		i = 0
		instance = ItemsStruct.new
		
		while i < times
			break unless instance.empty?
			i += 1
		end
	end
	
	x.report("Class#empty?") do |times|
		i = 0
		instance = ItemsClass.new
		
		while i < times
			break unless instance.empty?
			i += 1
		end
	end
	
	x.compare!
end

# This shows that in the presence of additional work, the difference is neglegible.
Benchmark.ips do |x|
	x.report("Struct#push_me_pull_you") do |times|
		i = 0
		a = A.new
		
		while i < times
			a.push_me_pull_you(i)
			i += 1
		end
	end
	
	x.report("Class#push_me_pull_you") do |times|
		i = 0
		b = B.new
		
		while i < times
			b.push_me_pull_you(i)
			i += 1
		end
	end
	
	x.compare!
end

Version data entries

60 entries across 60 versions & 1 rubygems

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