Node.js
Snapshot
Learn V8 snapshot and fast startup.
V8 snapshot
V8's snapshot feature loads the initial state (built-in objects, prototypes) from a pre-serialized string. This skips rebuilding built-ins from scratch when Node.js starts, resulting in faster startup.
A serializeSnapshot(state) function models this idea: it turns a state into a reloadable string. Example: serializeSnapshot({port: 3000, host: 'localhost'}) returns 'host=localhost;port=3000'. Keys are sorted so the output is deterministic. Object.keys(state).sort() gets the keys, .map(k => k + '=' + state[k]) turns each into key=value, .join(';') combines them. This is a simple model of V8's serialization logic.
Sorting the keys
To make snapshot output deterministic we sort the keys. Object.keys(state).sort() puts keys in alphabetical order. This way the same state always yields the same string; this is essential for snapshot comparison.
Example: the keys of {port: 3000, host: 'localhost'} come as ['port', 'host'] (insertion order). .sort() turns this into ['host', 'port']. Then .map(k => k + '=' + state[k]) yields ['host=localhost', 'port=3000']. .join(';') produces 'host=localhost;port=3000'. Sorting guarantees the same output even if insertion order differs. V8 snapshots rely on this determinism.
Exercise Write the snapshot serializer
Write function serializeSnapshot(state). Get and sort keys with const keys = Object.keys(state).sort(). Return keys.map(k => k + '=' + state[k]).join(';'). Print console.log(serializeSnapshot({port: 3000, host: 'localhost'})).
Show example solution
function serializeSnapshot(state) {
const keys = Object.keys(state).sort();
return keys.map(k => k + '=' + state[k]).join(';');
}
console.log(serializeSnapshot({port: 3000, host: 'localhost'}));
Test yourself
-
Complete the join call
keys.map(k => k + '=' + state[k]).____(';')
Show answer
keys.map(k => k + '=' + state[k]).join(';')
-
Match each concept to its description
- Snapshot
- Serializes initial state
- Object.keys
- Gets the keys
- .sort()
- Sorts alphabetically
- .join(';')
- Combines the array into a string
-
What does Object.keys({b: 1, a: 2}).sort() produce?
Object.keys({b: 1, a: 2}).sort()
- ['b', 'a']
- [1, 2]
- ['a', 'b']
- 'ab'
Show answer
['a', 'b'] — sort orders alphabetically: ['a', 'b'].
Next lesson: Summary - V8 internals