Skip to content

Commit 788330e

Browse files
committed
ActiveModel::Dirty: only reset original values for persisted records
If the record wasn't persisted in the first pace, this operation is useless and costly. Benchmark: https://gist.github.com/casperisfine/ae56bec1e7eecbff3a696b367e2bafa2 Before: ``` ruby 3.4.0preview2 (2024-10-07 master 32c733f57b) +YJIT +PRISM [arm64-darwin23] Warming up -------------------------------------- ActiveRecord 4.048k i/100ms Calculating ------------------------------------- ActiveRecord 40.231k (± 2.2%) i/s (24.86 μs/i) - 202.400k in 5.033380s ``` After: ``` ruby 3.4.0preview2 (2024-10-07 master 32c733f57b) +YJIT +PRISM [arm64-darwin23] Warming up -------------------------------------- ActiveRecord 6.973k i/100ms Calculating ------------------------------------- ActiveRecord 66.902k (± 7.1%) i/s (14.95 μs/i) - 334.704k in 5.035269s ```
1 parent aeb0828 commit 788330e

File tree

2 files changed

+2
-1
lines changed

2 files changed

+2
-1
lines changed

activemodel/lib/active_model/dirty.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ module Dirty
247247

248248
def initialize_dup(other) # :nodoc:
249249
super
250-
if self.class.respond_to?(:_default_attributes)
250+
if other.persisted? && self.class.respond_to?(:_default_attributes)
251251
@attributes = self.class._default_attributes.map do |attr|
252252
attr.with_value_from_user(@attributes.fetch_value(attr.name))
253253
end

activemodel/test/cases/dirty_test.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
class DirtyTest < ActiveModel::TestCase
77
class DirtyModel
8+
include ActiveModel::API
89
include ActiveModel::Dirty
910
define_attribute_methods :name, :color, :size, :status
1011

0 commit comments

Comments
 (0)