Skip to content

Instantly share code, notes, and snippets.

@miharekar
Created March 6, 2015 17:08
Show Gist options
  • Save miharekar/507c03619e6cacaed761 to your computer and use it in GitHub Desktop.
Save miharekar/507c03619e6cacaed761 to your computer and use it in GitHub Desktop.
Ruby: Struct vs Class performance
require 'benchmark/ips'
Benchmark.ips do |x|
SingleFilterStruct = Struct.new(:method, :values) do
def call(value)
Array(value).any? { |v| v.send(method, *values) }
end
end
class SingleFilterClass
def initialize(method, values)
@method = method
@values = values
end
def call(value)
Array(value).any? { |v| v.send(@method, *@values) }
end
end
x.report("struct") do
filter = SingleFilterStruct.new(:eql?, 'aa')
filter.call('aa')
end
x.report("class") do
filter = SingleFilterClass.new(:eql?, 'aa')
filter.call('aa')
end
x.compare!
end
@miharekar
Copy link
Author

Calculating -------------------------------------
              struct    63.273k i/100ms
               class    66.284k i/100ms
-------------------------------------------------
              struct      1.069M (± 5.2%) i/s -      5.378M
               class      1.094M (± 5.2%) i/s -      5.502M

Comparison:
               class:  1094260.4 i/s
              struct:  1069255.2 i/s - 1.02x slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment