1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activesupport/test/core_ext/object
Daniel Pepper 964e7ad156
deep dup
Is there a reason we're only taking this short cut for frozen strings and not other immutable objects commonly used as hash keys (eg. symbols and integers)?

initial tests suggest a ~30% performance improvement...

```

require 'benchmark'

class Object
  def deep_dup
    dup
  end
  alias deep_dup_all deep_dup
end

class Hash
 def deep_dup
   hash = dup
   each_pair do |key, value|
     if key.frozen? && ::String === key
       hash[key] = value.deep_dup
     else
       hash.delete(key)
       hash[key.deep_dup] = value.deep_dup
     end
   end
   hash
 end

 def deep_dup_all
   hash = dup
   each_pair do |key, value|
     if key.frozen?
       hash[key] = value.deep_dup_all
     else
       hash.delete(key)
       hash[key.deep_dup_all] = value.deep_dup_all
     end
   end
   hash
 end
end

data = Hash[('aaa'..'zzz').map {|k| [k.to_sym, k]}]

control = Benchmark.realtime do
  30.times { data.deep_dup }
end

experiment = Benchmark.realtime do
  30.times { data.deep_dup_all }
end

puts "%.3f  v  %.3f  => %d%% speed up" % [ control, experiment, (control - experiment) / control * 100 ]

```
2020-08-17 15:24:47 -07:00
..
acts_like_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
blank_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
deep_dup_test.rb deep dup 2020-08-17 15:24:47 -07:00
duplicable_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
inclusion_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
instance_variables_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
json_cherry_pick_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
json_gem_encoding_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
to_param_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
to_query_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00
try_test.rb allow running each test with pure ruby path/to/test.rb 2019-12-18 08:49:19 -06:00