Sha256: e4e94bc6ffdd6a39733d4a99982d75bcb453003987c9aa78aa433616972893ac

Contents?: true

Size: 1.38 KB

Versions: 13

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

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

13 entries across 13 versions & 1 rubygems

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