I have written a task that will run periodically to recalculate and update the information in a particular column of an Active Record model. Frequently, the newly calculated object (it’s a json-encoded hash, if that matters) will be the same as the existing objects. In such cases, I suspect that it may be more efficient to check for this identity and abort the save rather than saving. Thus, I am considering using self.save! if changed? rather than merely self.save!. My questions are:
- Does Active Record do this automatically, so that these two commands are actually equivalent?
- If, as I suspect, it does not, am I likely to save CPU time by adding the
if changed?condition?
(I apologize if I’ve misused some terminology here. I’m new to the game.)
No db query is made, here is a simple example using Rails 3.1.1 in console:
Edit:
So it’s faster with
if changed?.