Skip to content

Instantly share code, notes, and snippets.

@simcap
Last active August 29, 2015 14:09
Show Gist options
  • Save simcap/622cac189c9cd0f8665d to your computer and use it in GitHub Desktop.
Save simcap/622cac189c9cd0f8665d to your computer and use it in GitHub Desktop.
Defining a fast immutable Struct
# Defining a fast immutable struct while
# keeping Struct value object behaviour
class ImmutableStruct < Struct
undef []=, send
def self.inherited(subclass)
subclass.instance_methods.grep(/\w=/) do |setter|
undef_method setter
end
end
end
# Make an immutable Struct by subclassing only
class MyImmutable < ImmutableStruct.new(:one, :two); end
o = MyImmutable.new(1,2)
p o.respond_to?('[]=') # => false
p o.respond_to?('one=') # => false
p o.respond_to?('two=') # => false
p o.respond_to?('send') # => false
# Bencharking against the Struct
require 'benchmark/ips'
RegularStruct = Struct.new(:flip, :flap)
Benchmark.ips do |x|
x.report('Immutable Struct:') do
MyImmutable.new(1,2)
end
x.report('Regular Struct:') do
RegularStruct.new(1,2)
end
x.compare!
end
__END__
Calculating -------------------------------------
Immutable Struct: 103.865k i/100ms
Regular Struct: 102.135k i/100ms
-------------------------------------------------
Immutable Struct: 3.168M (± 2.7%) i/s - 15.891M
Regular Struct: 3.394M (± 2.0%) i/s - 17.057M
Comparison:
Regular Struct:: 3394240.6 i/s
Immutable Struct:: 3168228.5 i/s - 1.07x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment