man javascript/objects-vs-map
Objects vs Map in V8: how keys are stored and ordered
Counting things in JavaScript usually starts with one of two lines:
counts[key] = (counts[key] ?? 0) + 1; // plain object
counts.set(key, (counts.get(key) ?? 0) + 1); // Map
Both work. They differ in what comes back out. The object returns its keys as
strings, and if those keys are integers it returns them sorted. The Map returns
them as they went in, in the order they went in. This article follows both through
the ECMAScript specification and through V8 12.9.202.28, the engine in Node
23.11.0. Node ships it as 12.9.202.28-node.14; I compared every V8 file cited
below with Node’s deps/v8 copy at v23.11.0 and they are identical.
The order an object gives back
Here is an object with string keys and integer-looking keys mixed:
const o = {};
o.b = 1;
o[10] = 1;
o.a = 1;
o[2] = 1;
o["01"] = 1;
o[-1] = 1;
o[4294967295] = 1;
o[4294967294] = 1;
console.log(Object.keys(o));
const m = new Map();
for (const k of ["b", 10, "a", 2]) m.set(k, 1);
console.log([...m.keys()]);
$ node keys.mjs
[ '2', '10', '4294967294', 'b', 'a', '01', '-1', '4294967295' ]
[ 'b', 10, 'a', 2 ]
The object order comes straight from the spec. OrdinaryOwnPropertyKeys
(section 10.1.11.1) builds the key list in three passes:
- every key that is an array index, in ascending numeric order;
- every other string key, in the order the properties were created;
- every symbol key, in creation order.
An array index is a canonical integer string from 0 to 2³² − 2. That explains
the odd ones out. "01" and "-1" aren’t canonical non-negative integers, so
they are ordinary strings and keep their place in line. 4294967294 is 2³² − 2,
the largest array index, so it sorts with the numbers. 4294967295 is one too
big and falls back into creation order.
Object.keys, Object.entries and Object.values all start from that
list. EnumerableOwnProperties (7.3.23) calls
[[OwnPropertyKeys]] and filters it in list order.
How V8 stores an object’s keys
V8 keeps the two kinds of key in separate stores. Named properties go in the object’s properties, described by its hidden class or kept in a dictionary. Array-index keys go in a separate elements backing store. The V8 blog post “Fast properties in V8” (2017) describes the split; the code below shows how it plays out for a counting object.
The elements store has two main shapes. A fast store is a plain array
indexed by the key, with holes for missing keys. A dictionary store is a
NumberDictionary, a hash table of key, value and property details (three
slots per entry, kEntrySize = 3 in dictionary.h).
Which one you get is a space trade-off. When you write index i beyond the
current capacity, ShouldConvertToSlowElements in js-objects-inl.h first
checks the gap:
if (index - capacity >= JSObject::kMaxGap) return true;
kMaxGap is 1024 (js-objects.h). So the very first write to an empty object
decides it:
for (const i of [1023, 1024]) {
const o = {};
o[i] = 1;
console.log(i, %HasDictionaryElements(o));
}
$ node --allow-natives-syntax slow.mjs
1023 false
1024 true
The way back is in ShouldConvertToFastElements in js-objects.cc. On each
new index it compares the dictionary’s size (capacity × 3) with the array that
would replace it (largest key + 1), and switches back when the dictionary saves
less than half:
// Turn fast if the dictionary only saves 50% space.
return 2 * dictionary_size >= *new_capacity;
I counted 100,000 random integers drawn from 50,000 values between 10 and 99,999 into a plain object, and logged every change of mode:
import { readFileSync } from "node:fs";
const ints = readFileSync(process.argv[2], "utf8").trim().split("\n").map(Number);
const counts = {};
let mode = null;
let keys = 0;
for (let i = 0; i < ints.length; i++) {
if (counts[ints[i]] === undefined) keys++;
counts[ints[i]] = (counts[ints[i]] ?? 0) + 1;
const dict = %HasDictionaryElements(counts);
if (dict !== mode) {
console.log(`after ${i + 1} numbers, ${keys} keys: dictionary=${dict}`);
mode = dict;
}
}
$ node --allow-natives-syntax flips.mjs wide.txt
after 1 numbers, 1 keys: dictionary=true
after 12317 numbers, 10925 keys: dictionary=false
The first key was 1190, more than 1024 past an empty store, so the object started as a dictionary. Once about 11,000 of the possible 100,000 slots were filled, a flat array became the cheaper option. V8 switched, and the object stayed fast for the rest of the run.
Where the sorted order comes from
When you ask for keys, KeyAccumulator::CollectOwnKeys in keys.cc collects
element indices first and property names second, which is the spec’s order.
How the indices come out sorted depends on the store. For a fast store,
DirectCollectElementIndicesImpl in elements.cc checks every slot from index
0 up to the largest index, holes included, so the keys come out sorted for
free. A dictionary store is a hash
table in no particular order, so elements.cc sets needs_sorting for
dictionary elements and calls SortIndices, a std::sort over the
collected keys. Named properties in dictionary mode have the opposite problem:
CopyEnumKeysTo in keys.cc sorts them by their stored enumeration index to
get creation order back.
Keys come out of Object.keys and Object.entries as strings, because the
spec says property keys are strings or symbols. The same function converts each
index with SizeToString, going through V8’s number-to-string cache for small
enough indices.
How a Map is built
The spec only says that a Map must give “access times that are sublinear on
the number of elements” (section 24.1) and that forEach visits entries “in
key insertion order”. V8 meets both with OrderedHashMap. The comment at the
top of ordered-hash-table.h names its origin, the “Deterministic Hash Table”
described by Jason Orendorff, originally attributed to Tyler Close.
The whole table is one FixedArray:
[ element count | deleted count | bucket count ]
[ bucket 0 | bucket 1 | ... ] index of first entry in each bucket
[ key | value | chain ] [ key | value | chain ] ... entries, in insertion order
A new entry always goes at the end of the entry area. Its chain slot holds
the entry that used to head its bucket, and the bucket now points at the new
entry. Lookup hashes the key, picks a bucket with hash & (buckets - 1), and
follows the chain. Iteration ignores the buckets. The Map iterator in
builtins-collections-gen.cc steps through the entry area by index with
NextSkipHashTableHoles, which is why insertion order costs nothing.
The constants:
kInitialCapacity = 4.new Map()allocates a table for 4 entries (AllocateOrderedHashMapincode-stub-assembler.cc).kLoadFactor = 2: two entries per bucket, so 4 entries use 2 buckets.EnsureCapacityForAddinginordered-hash-table.ccrebuilds the table when the entry area is full. If at least half of it is deleted entries, the new table has the same capacity and the holes are squeezed out. Otherwise the capacity doubles.Shrinkhalves the capacity when fewer than a quarter of the slots are live.
Deleting doesn’t move anything. Delete in ordered-hash-table.cc overwrites
the entry’s slots with a hole marker and bumps the deleted count. A key deleted and set again goes to the back:
const m = new Map([[3, "a"], [1, "b"], [2, "c"]]);
m.delete(3);
m.set(3, "a");
console.log([...m.keys()]);
$ node reorder.mjs
[ 1, 2, 3 ]
Rebuilding a table while an iterator is running would lose its place. The header describes the fix. The old table becomes “obsolete” and keeps a pointer to its replacement plus the indexes of the removed holes, so a live iterator can translate its position into the new table.
Map keys stay what they are
Map.prototype.set in builtins-collections-gen.cc has a lookup path per key
type: small integers (Smis), strings, heap numbers, BigInts and everything
else. Before any of them, NormalizeNumberKey turns a -0 key into the Smi
0, which implements the spec’s CanonicalizeKeyedCollectionKey. Keys are
compared with SameValueZero, so NaN finds NaN:
const z = new Map([[-0, "zero"]]);
console.log(Object.is([...z.keys()][0], -0), z.get(0));
const n = new Map([[NaN, "nan"]]);
console.log(n.get(0 / 0));
$ node zero.mjs
false zero
nan
Small integer keys are hashed by ComputeUnseededHash, an integer mixing
function of shifts, xors and a multiply by 2057, masked to 30 bits.
Which one is faster for counting
It depends on the keys. I timed both counting loops in one process, best of 30 runs, on two inputs of 100,000 integers: the 43,282-distinct-key set from above, and one with only 100 distinct values from 10 to 109.
import { readFileSync } from "node:fs";
const ids = readFileSync(process.argv[2], "utf8").trim().split("\n").map(Number);
function obj(ids) { const c = {}; for (const id of ids) c[id] = (c[id] ?? 0) + 1; return c; }
function map(ids) { const c = new Map(); for (const id of ids) c.set(id, (c.get(id) ?? 0) + 1); return c; }
for (const [name, f] of [["object", obj], ["Map", map]]) {
let best = Infinity;
for (let r = 0; r < 30; r++) { const t = performance.now(); f(ids); best = Math.min(best, performance.now() - t); }
console.log(`${name.padEnd(7)} best of 30: ${best.toFixed(2)} ms`);
}
$ node count.mjs wide.txt
object best of 30: 5.98 ms
Map best of 30: 4.33 ms
$ node count.mjs narrow.txt
object best of 30: 0.69 ms
Map best of 30: 2.51 ms
With 100 small keys the object’s elements store is a short array and
counts[key] is an array access, about 3.6 times faster than the Map’s hash
and chain walk. With keys spread up to 99,999 the Map wins. The same script on
Deno 2.9.8, which embeds V8 15.0, gave 3.20 ms for the object and 4.06 ms for the
Map on the wide input, and 0.47 ms against 2.56 ms on the narrow one. On that
runtime the object is faster on both inputs. I didn’t look into why.
Speed aside, the choice comes down to what you need back, numbers in arrival order from a Map, or strings in numeric order from an object.
Curious facts
4294967294sorts as a number inObject.keysand4294967295doesn’t. The first is the largest array index (2³² − 2); the second is just a string.o[1024] = 1on an empty object creates a hash table for its elements, whileo[1023] = 1creates an array of 1,552 slots (%DebugPrintshowsFixedArray[1552]).NewElementsCapacitygrows to the needed length plus half, plus 16. The cutoff iskMaxGap.Object.groupBy(ES2024) returns an object with anullprototype, so a group called"toString"can’t collide with an inherited method. Node prints it as[Object: null prototype] { odd: [ 1, 3 ], even: [ 2 ] }.- A
Mapentry set while you are iterating that Map is visited by the same loop. The spec’sforEachre-reads the entry count after every callback. Object.keyson an object with fast elements checks every slot of its elements store, holes included.%DebugPrintshows the counting object above withFixedArray[150014]: 150,014 slots checked to report 43,282 keys.
History
- ES2015 adds
Mapand defines[[OwnPropertyKeys]]order: integer indices ascending, then strings and symbols in creation order. - ES2019:
EnumerableOwnPropertyNames, behindObject.keys, still ends with “Order the elements of properties so they are in the same relative order as would be produced by the Iterator” ofEnumerateObjectProperties, whose “mechanics and order of enumerating the properties is not specified”. - ES2020 drops that sentence, so
Object.keysandObject.entriesfollow[[OwnPropertyKeys]]. The same edition adds??. - ES2024 adds
Object.groupByandMap.groupBy.
Sources
- ECMAScript 2027 draft: OrdinaryOwnPropertyKeys, array index, EnumerableOwnProperties, Map objects, Map.prototype.set, Map.prototype.forEach, Object.groupBy
- Earlier editions: ES2015, ES2019, ES2020, ES2024
src/objects/ordered-hash-table.hat 12.9.202.28: design comment and layout,kInitialCapacity,kLoadFactor,HashToBucketsrc/objects/ordered-hash-table.cc:EnsureCapacityForAddingandShrink,Deletesrc/builtins/builtins-collections-gen.cc:NextSkipHashTableHolesin the Map iterator,ComputeUnseededHash,NormalizeNumberKey,MapPrototypeSetAllocateOrderedHashMapinsrc/codegen/code-stub-assembler.cckMaxGapinsrc/objects/js-objects.h,ShouldConvertToSlowElementsinjs-objects-inl.h,ShouldConvertToFastElementsinjs-objects.cc,NumberDictionaryShape::kEntrySizeNewElementsCapacityinsrc/objects/js-objects.h,DirectCollectElementIndicesImplinsrc/objects/elements.ccsrc/objects/keys.cc:CopyEnumKeysTo,CollectOwnKeys;SortIndicesfor dictionary elements insrc/objects/elements.cc- Node’s copy:
deps/v8at v23.11.0 - V8 blog, secondary: Fast properties in V8 (2017)
grep -rl /lib/javascript/objects-vs-map/
ls javascript/
- draft How V8 sorts arrays: TimSort in TorqueWhat Array.prototype.sort does in V8 12.9: string comparison by default, holes and undefined set aside, then a TimSort written in Torque with runs, binary insertion, merge invariants and galloping.