Sub topic 17
Choosing the Right Collection
This chapter assumes you have worked through the earlier chapters on Map, Set, WeakMap, and WeakSet. You should know their APIs, SameValueZero equality, and how weak references relate to garbage collection. Here we put those pieces together into a way to decide which one to use.
Four Questions That Decide It
Most choices come down to four questions:
- Do you need key-value pairs, or only membership? Use a Map or plain object for pairs. Use a Set for "is this value present?"
- What are your keys? Strings known ahead of time suit an object. Objects, numbers, or keys that users supply suit a Map.
- Should the collection keep its keys alive? If the data should disappear when the object it describes goes away, use a weak collection.
- Do you need to count, list, or serialize the contents? Weak collections can't do any of these. If you need them, use Map or Set.
Side-by-Side Comparison
| Need | Object | Map | Set | WeakMap | WeakSet |
|---|---|---|---|---|---|
| Any value as key | No, strings and symbols only | Yes | Yes, as members | Objects and non-registered symbols | Objects and non-registered symbols |
| `size` and iteration | Via `Object.keys` | Yes | Yes | No | No |
| Insertion order guaranteed | Partly, integer keys go first | Yes | Yes | No | No |
| Direct `JSON.stringify` | Yes | No, writes `{}` | No, writes `{}` | No | No |
| Lets keys be garbage collected | No | No | No | Yes | Yes |
| Frequent add and delete | Slower in many engines | Designed for it | Designed for it | Yes | Yes |
Common Mistakes
- Using an object as a dictionary of user input. A key like
"__proto__"or"constructor"can collide with inherited properties. A Map has no inherited keys. - Using a Map to cache data about DOM nodes or instances. The Map holds every key strongly, so removed nodes stay in memory. Use a WeakMap.
- Reaching for a WeakMap and then needing to list entries. If you ever need
sizeor a loop, the weak collection was the wrong choice. - Using an array for membership tests.
array.includesscans every element.set.hasis fast on average and makes your intent clear.
Applying the Rules
The code below shows each choice in a small program that tracks sessions.
// Fixed, record-shaped config: plain object (serializes cleanly)
const config = { maxSessions: 2, region: 'eu' };
// Lookup by numeric id with frequent add/delete: Map
const sessionsById = new Map();
// Membership only: Set
const bannedIds = new Set([42]);
// Per-object metadata that must not extend the object's life: WeakMap
const lastSeen = new WeakMap();
function openSession(id) {
if (bannedIds.has(id)) return null;
if (sessionsById.size >= config.maxSessions) return null;
const session = { id };
sessionsById.set(id, session);
lastSeen.set(session, Date.now());
return session;
}
openSession(1);
openSession(42);
openSession(2);
console.log(sessionsById.size); // 2
console.log([...sessionsById.keys()]); // [1, 2]
console.log(lastSeen.has(sessionsById.get(1))); // true
console.log(JSON.stringify(config)); // '{"maxSessions":2,"region":"eu"}'Exercise
You need to remember which form elements a user has already validated so you don't validate them twice. Elements can be removed from the page at any time, and you never need to list the validated ones. Which collection fits, and why?
Show answer
A WeakSet. You only need membership, the members are objects, and removed elements should be garbage collected instead of being kept alive by your tracking. You don't need iteration or size, so the limits of a WeakSet don't matter.
Exercise
An API returns word counts that you build from user-submitted text, and you must send the result back as JSON. Which collection do you use while counting, and how do you send it?
Show answer
Count with a Map, because the keys come from users and could include names like "_proto_". Convert it with Object.fromEntries(map) or [...map] before calling JSON.stringify, because stringifying the Map directly gives "{}".