Skip to content

Commit

Permalink
Speedup AttributeSet#deep_dup
Browse files Browse the repository at this point in the history
`Hash#deep_dup` is slower because it has to check if the keys are mutable.
In this case we know keys are all frozen strings so we can use `transform_values`
to skip dealing with keys.

Benchmark: https://gist.github.com/casperisfine/ae56bec1e7eecbff3a696b367e2bafa2

Before:

```
ruby 3.4.0preview2 (2024-10-07 master 32c733f57b) +YJIT +PRISM [arm64-darwin23]
Warming up --------------------------------------
        ActiveRecord     6.113k i/100ms
Calculating -------------------------------------
        ActiveRecord     61.941k (± 1.6%) i/s   (16.14 μs/i) -    311.763k in   5.034628s
```

After:

```
ruby 3.4.0preview2 (2024-10-07 master 32c733f57b) +YJIT +PRISM [arm64-darwin23]
Warming up --------------------------------------
        ActiveRecord     7.323k i/100ms
Calculating -------------------------------------
        ActiveRecord     73.195k (± 1.0%) i/s   (13.66 μs/i) -    366.150k in   5.002894s
```
  • Loading branch information
byroot committed Oct 16, 2024
1 parent aeb0828 commit 71ffcaf
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion activemodel/lib/active_model/attribute_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def freeze
end

def deep_dup
AttributeSet.new(attributes.deep_dup)
AttributeSet.new(attributes.transform_values(&:deep_dup))
end

def initialize_dup(_)
Expand Down

0 comments on commit 71ffcaf

Please sign in to comment.