Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bogdan
Created April 11, 2016 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bogdan/36187f53b1cd9d870572509e3c76b682 to your computer and use it in GitHub Desktop.
Save bogdan/36187f53b1cd9d870572509e3c76b682 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
require 'active_model'
# run this
# bundle exec ruby benchmark.rb && second_run=y bundle exec ruby benchmark.rb
class Person
include ActiveModel::Dirty
define_attribute_methods :name, :age
def initialize(name)
@name = name
end
def name=(val)
name_will_change! unless val == @name
@name = val
end
end
n = 2000000
if ENV['second_run']
module ActiveModel::Dirty
def attribute_changed?(attr, from: :none, to: :none)
result = changes_include?(attr)
result &&= from == __send__(attr) unless from == :none
result &&= to == changed_attributes[attr] unless to == :none
result
end
end
end
Benchmark.ips do |x|
x.hold! 'filename'
proc = Proc.new {
person = Person.new('tom')
person.name = 'bob'
n.times {
person.attribute_changed?(:name)
person.attribute_changed?(:age)
}
}
x.report("unchanged", &proc)
x.report("with nil", &proc)
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment