title: What causes the performance issue of with_lock?
body: <p>I'd like to understand what causes the performance impact.</p>
  
  <p>I have a test in RSpec where a function was called 1000 times. I notice that as the for loop progresses, calls became slower and slower.</p>
  
  <p>I nailed down the problem to be due to changing state inside a with_lock and outside of with_lock but can't explain why.</p>
  
  <p>This is the smallest code to reproduces this issue (it only happens with RSpec, running it through a controller and browsing to a page containing the test doesn't produce the slowdown):</p>
  
  <pre><code>c = Conversation.new
  c.save!
  
  for i in 0..1000
      puts i
      c.with_lock do
          c.pending = true
          c.save!
      end
      c.pending = false
      c.save!
  end
  </code></pre>
  
  <p>remove with_lock and no performance problem
  don't have the outside c.pending = false / c.save! and no performance problem</p>
  
  <p>Notice that there is only 1 entry in the database, not like we create tons of them.</p>
  
  <p>PS: I found this because I DO have a slow down in production that I need to reproduce, BUT it only happens for users who have a huge amount of Conversation objects (and it happens because of the with_lock, which according to the database calls I see in my controller in developement are a straight commit using the primary key (no notion of user having more or less Conversation objects)). I'm thinking the reload performing automatically at the end of with_lock could "explain" that one since I have a "has_many :conversations, through: :xxxxxx" relationship on my User object. But I really can't explain where the performance issue comes from in test env (and not sure about prod either).</p>