222 Chapter 6
Q&A: Is replaying expensive?
Q: Wow! Replaying the entire history each time? I thought
history of states was expensive!
Okay, that’s a valid concern. Let’s address it.
Yes, replaying the history is less ecient than keeping the
current state around in memory. This may or may not be a real
problem. The current state is calculated once per mutation, and
it is oen faster than repainting the UI in a browser. However,
sometimes it is not faster. We should consider how to speed it up.
First of all, if the history is short enough, in practice it’s not
a problem. For instance, replaying ten mutations could be very
quick.
For longer histories of 100 or 1,000 mutations, a common
practice is to keep a cache of the current state every n mutations
alongside the history. n could be as big or small as you want. I
typically choose n to be between 10 and 100, depending on how
much speed I want. With that cache, you only have to replay at
most the last nine mutations. Just pick the most recent cached
state and replay forward from there. Just know that these caches
are gaining speed at the expense of memory usage.
Another technique is to “close the books”. This is borrowed
from accounting, where at the end of the year, the physical book
is balanced and a new book is started for the new year. The bal-
ance from the end of the previous book is carried over to the new
book. The old book is “closed”, essentially becoming read-only.
If there is a natural boundary (like the nancial year) in your
domain on which to close the books, this technique could help
you not have to keep a long history in memory.
The important thing is to consider the tradeos. Are recording
the history, maintaining the intentions, and allowing undo valu-
able? Are they valuable enough to incur the cost?