MemHack
MemHack refers to the strategy of storing a user's Memory
object in global
to skip the JSON.parse()
normally required at first-access of Memory
in a tick, thus saving CPU every tick.
The way the Memory
object works is when first accessed in a game tick it is run though a JSON.parse()
which converts it to an object from its stored-as-a-string state, then after any changes have been made end-of-tick it is run though a JSON.stringify()
for storage. The user running the code pays for this parsing/stringifying with CPU the larger the Memory
object the more costly it is to process. You can read more about the Memory
object in Screep's offical docs.
So, MemHack works by creating an object in global
to store the Memory
object when initializing the global (and needs to be rebuilt if global dies due to code push, global reset, ect), then at the start of a tick (start of a user's main loop before any other Memory
related calls) deletes the 'normal' Memory
object and replaces it with the global version which due to global persisting between ticks does not need to be parsed. Then it sets RawMemory._parsed
to the current global MemHack obj as well, this insures changes are updated to the normal Memory
object, so that in the event of a global reset the Memory
object will still have the changes and, that the Memory watcher / console changing still work. It is important to note, that RawMemory._parsed
is not officially documented in the API however, it has been around and accessible for several years. It is possible for this strategy to become defunct in the future, should this be changed.
Code Examples
There are a few places you can view examples of this code: