Performance Optimization
Published by Brayan K
Master production-level performance optimization techniques for building fast, scalable applications.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Define the result, then count work you can actually observe
Consider repeated membership queries against a fixed list of IDs. A candidate optimization builds a Set once and reuses it. Before calling the candidate faster, verify that it returns the same answers and account for the preparation work. This example counts comparisons in our own search function, Set construction inputs and calls to has. It cannot observe the Set implementation’s internal comparisons.
const ids = ["A", "B", "C", "D"];
const wanted = ["A", "D", "Z", "A"];
let comparisons = 0;
function scan(id) {
for (const candidate of ids) {
comparisons++; // This is an actual equality check in our own loop.
if (candidate === id) return true;
}
return false;
}
const scanned = wanted.map(scan);
const index = new Set(ids); // Preparation happens once, outside the queries.
let lookups = 0;
const indexed = wanted.map(id => {
lookups++; // Count API calls, not hidden hash-table comparisons.
return index.has(id);
});
console.log("same", JSON.stringify(scanned) === JSON.stringify(indexed));
console.log("answers", indexed.join(","));
console.log("scan comparisons", comparisons);
console.log("construction inputs", ids.length);
console.log("has calls", lookups);
// ✅ Expected output:
// same true
// answers true,true,false,true
// scan comparisons 10
// construction inputs 4
// has calls 4The outputs establish equivalence for this fixture and report observable work. They do not establish milliseconds saved, internal hashing behavior or a universal speed ranking. JavaScript requires Set access to be sublinear on average; it does not mandate a particular data structure or constant time for every lookup. Map & Set owns Set equality and membership semantics.
Growth rate describes a workload, not a stopwatch reading
A pairwise scan visits every pair of distinct positions once. Its comparison count is n times n minus one divided by two. The program below measures that loop count for three input sizes. Big-O describes how work is bounded as inputs grow; it does not say that doubling every real input exactly doubles elapsed time.
function pairCount(size) {
let comparisons = 0;
for (let first = 0; first < size; first++) {
for (let second = first + 1; second < size; second++) {
comparisons++;
}
}
return comparisons;
}
for (const size of [4, 8, 16]) {
console.log(size, pairCount(size), size * (size - 1) / 2);
}
// ✅ Expected output:
// 4 6 6
// 8 28 28
// 16 120 120Input distribution matters as well as size. A search that exits on the first match does less work for an early match than for a miss. A benchmark containing only early matches may not represent the application’s actual queries.
function countSearch(values, target) {
let comparisons = 0;
for (const value of values) {
comparisons++;
if (value === target) return { found: true, comparisons };
}
return { found: false, comparisons };
}
for (const target of ["A", "D", "Z"]) {
console.log(target, JSON.stringify(countSearch(["A", "B", "C", "D"], target)));
}
// ✅ Expected output:
// A {"found":true,"comparisons":1}
// D {"found":true,"comparisons":4}
// Z {"found":false,"comparisons":4}For a one-off search, building an index can cost more than it saves. For many searches against unchanged data, its preparation can be reused. Measure the scenario you intend to ship rather than excluding setup from one candidate but charging it to the other.
const ids = ["A", "B", "C"];
const wanted = ["A", "Z", "C"];
let rebuilt = 0;
const repeated = wanted.map(id => {
rebuilt++;
return new Set(ids).has(id);
});
let prepared = 0;
prepared++;
const index = new Set(ids);
const reused = wanted.map(id => index.has(id));
console.log("same", JSON.stringify(repeated) === JSON.stringify(reused));
console.log("constructed", rebuilt, prepared);
// ✅ Expected output:
// same true
// constructed 3 1An optimization must preserve the contract that matters
Equivalent membership does not imply equivalent output order. If duplicates must appear in the order they first repeat, sorting the result to make a test pass hides a change in behavior. State the ordering contract before choosing an algorithm.
const ids = ["A", "B", "B", "A"];
const firstOriginal = [];
for (let index = 0; index < ids.length; index++) {
if (ids.slice(index + 1).includes(ids[index]) &&
!firstOriginal.includes(ids[index])) firstOriginal.push(ids[index]);
}
const seen = new Set();
const repeated = new Set();
const firstRepeat = [];
for (const id of ids) {
if (seen.has(id) && !repeated.has(id)) {
firstRepeat.push(id);
repeated.add(id);
}
seen.add(id);
}
console.log(firstOriginal.join(","));
console.log(firstRepeat.join(","));
console.log("same order", JSON.stringify(firstOriginal) === JSON.stringify(firstRepeat));
console.log("same sorted", JSON.stringify([...firstOriginal].sort()) === JSON.stringify([...firstRepeat].sort()));
// ✅ Expected output:
// A,B
// B,A
// same order false
// same sorted trueAlso check mutation and identity. A candidate that sorts the caller’s array may produce the desired values while breaking another part of the program that relies on the original order.
const input = [3, 1, 2];
const sorted = input.sort((a, b) => a - b);
console.log(sorted.join(","));
console.log(input.join(","));
console.log(sorted === input);
const other = [3, 1, 2];
const copy = [...other].sort((a, b) => a - b);
console.log(copy.join(","));
console.log(other.join(","));
// ✅ Expected output:
// 1,2,3
// 1,2,3
// true
// 1,2,3
// 3,1,2A copied array has its own cost, but removing that copy changes the API unless mutation is allowed. Spread & Rest Operators owns shallow copying. map, filter & reduce owns collection transformation contracts.
const values = [NaN];
console.log(values.includes(NaN));
console.log(values.indexOf(NaN) !== -1);
console.log(new Set(values).has(NaN));
// ✅ Expected output:
// true
// false
// trueincludes and Set membership agree for NaN here, while indexOf does not find it. The lesson’s final ID algorithm accepts only strings, making its equality contract explicit rather than pretending every replacement works for arbitrary values.
Keep validation inside the workload you promise to support
If the optimized path promises an array of string IDs, validate that contract rather than coercing unexpected input into different keys. Validation itself is work: include it in the comparison when callers rely on it.
function prepareIndex(ids) {
if (!Array.isArray(ids)) throw new TypeError("Expected an array of string IDs");
const index = new Set();
for (const id of ids) {
if (typeof id !== "string") throw new TypeError("Expected an array of string IDs");
index.add(id);
}
return index;
}
prepareIndex(["A", 1]);
// ✅ Expected error:
// TypeError: Expected an array of string IDsThe rejected input does not become the strings A and 1. Input conversion would be a different behavior and needs an explicit API decision. Error Handling owns how callers recover from such a documented input failure.
Avoid work only when the question permits it
const values = [2, 4, 6, 8];
let allChecks = 0;
const byFilter = values.filter(value => { allChecks++; return value > 0; }).length > 0;
let someChecks = 0;
const bySome = values.some(value => { someChecks++; return value > 0; });
console.log(byFilter, bySome);
console.log(allChecks, someChecks);
// ✅ Expected output:
// true true
// 4 1some answers whether any match exists. It would be the wrong replacement if the caller needs every match or expects a side effect for each item. Fewer callback calls are observable; whether this matters in the real workload is a separate measurement.
A cache is correct only while its dependencies and lifetime are correct
let rate = 2;
const cache = new Map();
function quote(quantity) {
if (cache.has(quantity)) return cache.get(quantity);
const result = quantity * rate;
cache.set(quantity, result);
return result;
}
console.log(quote(3));
rate = 4;
console.log("cached", quote(3));
console.log("current rule", 3 * rate);
// ✅ Expected output:
// 6
// cached 6
// current rule 12The result depends on both quantity and rate, but the cache key includes only quantity. One repair is to give each fixed rate its own cache and create a new calculator when the rule changes. Other contracts might include the rate in the key or explicitly invalidate entries.
function calculator(rate) {
const cache = new Map();
let calculations = 0;
return {
quote(quantity) {
if (cache.has(quantity)) return cache.get(quantity);
calculations++;
const result = quantity * rate;
cache.set(quantity, result);
return result;
},
count: () => calculations
};
}
const oldRule = calculator(2);
const newRule = calculator(4);
console.log(oldRule.quote(3), oldRule.quote(3), oldRule.count());
console.log(newRule.quote(3), newRule.count());
// ✅ Expected output:
// 6 6 1
// 12 1This small demonstration has no eviction and assumes finite numeric inputs. A long-lived cache accepting arbitrary quantities needs an explicit retention policy. Closures and Scope owns the retained-state mechanism, and JavaScript Memory Management & Garbage Collection owns memory investigation. Caching also changes object identity if the stored result is mutable; reusing it may be a behavioral change, not merely a speed improvement.
Measure the application and distinguish latency from responsiveness
For a browser application, record a representative interaction in the Performance panel, locate the expensive work, change one suspected cause and record the same interaction again. Compare behavior and workload as well as the profile. Include preparation, transfer, rendering and cleanup when they belong to the user’s operation. Use multiple runs and representative data sizes; one unusually fast or slow run is weak evidence.
Keep diagnostic logging outside the measured work. Account for warm-up, browser extensions, background activity and device differences. CPU throttling can help explore slower conditions, but it is a simulation rather than a native-device test. A developer’s fast desktop is not evidence that a phone has the same experience.
Elapsed completion time and time until the interface can respond are different outcomes. Splitting one synchronous function into several ordinary function calls does not yield the main thread. Adding async alone does not move CPU work to another thread. Event Loop, Microtasks & Async Internals owns scheduling; Web Workers (Background Threads) owns worker communication and its costs.
DOM reads and writes, rendering, request timing and bundle costs can dominate a tiny loop optimization. JavaScript Performance Optimization Techniques owns deeper profiling and browser-specific techniques. The deterministic examples here do not print stopwatch values or claim a particular device speed.
Guided exercise: report each repeated ID once
For string IDs, track which IDs have been seen and which repeats have already been reported. Fill the membership checks and the state update. Keep the order in which each ID first repeats.
const seen = new Set();
const reported = new Set();
const output = [];
for (const id of ["A", "B", "B", "A", "B"]) {
if (seen.___(id) && !reported.has(id)) { // 👉 replace ___ with has
output.push(id);
reported.___(id); // 👉 replace ___ with add
}
seen.___(id); // 👉 replace ___ with add
}
console.log(output.join(","));
// ✅ Expected output:
// B,AIndependent brief: replace a repeated scan while preserving order
Write repeatedIds(ids). Require an array whose entries are strings; reject any other input with TypeError("Expected an array of string IDs"). Return a new array containing each repeated ID once, in the order of its first repeated occurrence. Keep the input unchanged. Use one traversal of the IDs and a bounded number of Set method calls per ID. Empty input and unique input return an empty array.
Compare against the simple reference for empty, unique, consecutive, interleaved and all-equal fixtures. Compare the arrays in order without sorting. Check the original input and invalid types. The reference is an oracle for the stated contract, not a benchmark competitor with identical implementation.
function repeatedIds(ids) {
if (!Array.isArray(ids)) throw new TypeError("Expected an array of string IDs");
const seen = new Set();
const reported = new Set();
const output = [];
for (const id of ids) {
if (typeof id !== "string") throw new TypeError("Expected an array of string IDs");
if (seen.has(id) && !reported.has(id)) {
output.push(id);
reported.add(id);
}
seen.add(id);
}
return output;
}
function reference(ids) {
const output = [];
for (let index = 0; index < ids.length; index++) {
const seenBefore = ids.slice(0, index).includes(ids[index]);
if (seenBefore && !output.includes(ids[index])) output.push(ids[index]);
}
return output;
}
for (const ids of [
[], ["A", "B"], ["A", "A", "B", "B"],
["A", "B", "B", "A"], ["A", "A", "A"],
["a", "A", "a", "A"], ["", "", "A"]
]) {
const before = JSON.stringify(ids);
const actual = repeatedIds(ids);
console.log(JSON.stringify(actual),
JSON.stringify(actual) === JSON.stringify(reference(ids)),
JSON.stringify(ids) === before);
}
for (const invalid of [null, "A", ["A", 1], new Array(1)]) {
try { repeatedIds(invalid); } catch (error) { console.log(error.message); }
}
// ✅ Expected output:
// [] true true
// [] true true
// ["A","B"] true true
// ["B","A"] true true
// ["A"] true true
// ["a","A"] true true
// [""] true true
// Expected an array of string IDs
// Expected an array of string IDs
// Expected an array of string IDs
// Expected an array of string IDsThe sets retain at most the distinct IDs in this call, and the loop performs a fixed maximum number of Set operations per input item. Those are structural observations. The engine’s internal lookup costs and the application’s elapsed time still need measurement. The test with interleaved repeats prevents a first-original-order implementation from passing accidentally.
Practice quiz
What does this complete program print? let comparisons = 0; for (const value of ["A", "B", "C"]) { comparisons++; if (value === "A") break; } console.log(comparisons);
- 1
- 0
- 2
- 3
Answer: 1. The first value matches, so this actual loop performs one comparison.
What does this complete program print? let pairs = 0; for (let i = 0; i < 4; i++) { for (let j = i + 1; j < 4; j++) pairs++; } console.log(pairs);
- 4
- 6
- 8
- 16
Answer: 6. The six distinct position pairs are visited exactly once.
What does this complete program print? let builds = 0; const ids = ["A", "B"]; for (const id of ["A", "B", "Z"]) { builds++; new Set(ids).has(id); } console.log(builds);
- 1
- 2
- 3
- 0
Answer: 3. The constructor is inside the query loop, so preparation is repeated three times.
What does this complete program print? const ids = ["A", "B", "B", "A"]; const seen = new Set(), reported = new Set(), output = []; for (const id of ids) { if (seen.has(id) && !reported.has(id)) { output.push(id); reported.add(id); } seen.add(id); } console.log(output.join(","));
- A,B
- A,B,B,A
- B,B,A
- B,A
Answer: B,A. B repeats before A, and each repeated ID is emitted once.
What does this complete program print? const values = [3, 1, 2]; values.sort((a, b) => a - b); console.log(values.join(","));
- 1,2,3
- 3,1,2
- 1,3,2
- 2,1,3
Answer: 1,2,3. sort mutates the original array; result equivalence alone would miss that behavior.
What does this complete program print? console.log([NaN].includes(NaN)); console.log([NaN].indexOf(NaN));
- false -1
- true -1
- true 0
- false 0
Answer: true -1. includes matches NaN, while indexOf does not. Equality rules matter when replacing operations.
What does this complete program print? let calls = 0; const found = [2, 4, 6].some(value => { calls++; return value > 0; }); console.log(found, calls);
- true 3
- false 3
- true 1
- true 0
Answer: true 1. some stops when its existence question is answered.
What does this complete program print? let rate = 2; const cached = 3 * rate; rate = 4; console.log(cached, 3 * rate);
- 12 12
- 6 6
- 12 6
- 6 12
Answer: 6 12. An earlier result does not update automatically when an input dependency changes.
Continue this course
- Previous: Design Patterns
- Next: Deep Dive into JavaScript Execution Context & Call Stack — How JS engines execute code, create frames, and manage the call stack
- Quick reference: JavaScript cheat sheet