Map.getOrInsert() Benchmark
Chrome 143 ships Map.prototype.getOrInsert() and getOrInsertComputed(). This benchmark compares the new insert-if-missing helpers with two classic counter patterns over 50,000 random words and reports min, median, and max time across 5 runs.
Benchmark Runner
50,000 random words × 5 runs each. Min / median / max shown for each pattern.
1. Classic has/get/set
—
ms median
min — · max —
2. get-or-default
—
ms median
min — · max —
3. getOrInsert()
—
ms median
min — · max —
Implementation Reference
// Pattern 1: Classic has/get/set
const map = new Map();
for (const word of words) {
if (map.has(word)) {
map.set(word, map.get(word) + 1);
} else {
map.set(word, 1);
}
}
// Pattern 2: Get-or-default (nullish coalescing)
const map = new Map();
for (const word of words) {
map.set(word, (map.get(word) ?? 0) + 1);
}
// Pattern 3: Map.prototype.getOrInsert() — Chrome 143
// getOrInsert(key, value)
// returns the existing value or inserts and returns the default.
const map = new Map();
for (const word of words) {
map.set(word, map.getOrInsert(word, 0) + 1);
}
// getOrInsertComputed(key, factory) lazily creates defaults:
const groups = new Map();
for (const word of words) {
groups.getOrInsertComputed(word[0], () => []).push(word);
}
// Polyfill used on browsers without the native methods:
if (typeof Map.prototype.getOrInsert !== 'function') {
Map.prototype.getOrInsert = function(key, value) {
if (this.has(key)) return this.get(key);
this.set(key, value);
return value;
};
}
if (typeof Map.prototype.getOrInsertComputed !== 'function') {
Map.prototype.getOrInsertComputed = function(key, factory) {
if (this.has(key)) return this.get(key);
const value = factory(key);
this.set(key, value);
return value;
};
}
Use-case Presets
Each preset runs one of the shipped get-or-insert helpers on a distinct real-world use case.
Word Frequency
Count occurrences of each word across a corpus with getOrInsert.
Click Run to execute.
Event Counter
Track per-event-type counts from a stream of 10,000 browser events.
Click Run to execute.
Nested Map Builder
Build a Map<category, Map<key, count>> and lazily create each inner Map.
Click Run to execute.
see also
- Upsert — feature index
- Counter & group-by patterns
- ChromeStatus entry
- TC39 proposal spec