aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/model_schema.rb
diff options
context:
space:
mode:
authorArthur Chui <arthur.chui@gmail.com>2017-07-24 22:36:29 -0700
committerArthur Chui <arthur.chui@gmail.com>2017-07-25 10:20:01 -0700
commit34667957f40e3b2f29cacbb3b699c933b9e5ed67 (patch)
tree9895c281dcf73d8a0ff3837fa944e6e7c0a457c7 /activerecord/lib/active_record/model_schema.rb
parent9569a0cde832fcd0aaa078ebb1067e6dd3e22d90 (diff)
downloadrails-34667957f40e3b2f29cacbb3b699c933b9e5ed67.tar.gz
rails-34667957f40e3b2f29cacbb3b699c933b9e5ed67.tar.bz2
rails-34667957f40e3b2f29cacbb3b699c933b9e5ed67.zip
Use hash lookup for deleting existing associations from `target`
`Array#delete` searches for all occurrences in the `target` array. When performing `dependent: :destroy` in active_record/associations/collection_association, the loop becomes O(N^2). It is particularly slow when destroying large amount of associations (e.g. 10K records). Either `Hash` or `Set` can optimize the loop to O(N). `Hash` is slightly faster in this simple usage. ```ruby class Dummy; end num = 10_000 test1a = num.times.map { Dummy.new }; nil test1b = test1a.dup test2a = num.times.map { Dummy.new }; nil test2b = test2a.dup Benchmark.ips do |x| x.config(stats: :bootstrap, confidence: 95) x.report("hash") do hash = test1a.group_by { |r| r } test1b.select! { |r| !hash[r] } end x.report("array") do test2a.each { |r| test2b.delete(r) } end x.compare! end ``` ``` Calculating ------------------------------------- hash 11.000 i/100ms array 1.000 i/100ms ------------------------------------------------- hash 114.586 (±16.6%) i/s - 561.000 array 1.710k (±10.3%) i/s - 8.377k Comparison: array: 1710.4 i/s hash: 114.6 i/s - 14.93x slower ```
Diffstat (limited to 'activerecord/lib/active_record/model_schema.rb')
0 files changed, 0 insertions, 0 deletions