- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Performance Basics
JavaScript Performance
JavaScript Performance Basics
Fast code starts with measuring, not guessing where the slow part is.
Intuition about what is slow is wrong surprisingly often.
The next lessons cover specific techniques; this one covers the mindset.
Example
Example
javascript
const started = Date.now();
let total = 0;
for (let i = 0; i < 100000; i++) {
total += i;
}
const elapsed = Date.now() - started;
console.log(elapsed >= 0);
console.log(typeof elapsed);Timing the work is the first step, always.
Measure First
Guessing which part of a program is slow is usually wrong.
Timing narrows it down to the actual cause.
Only optimise the part that measuring shows is actually slow.
Syntax
Syntax
javascript
const started = Date.now();
// work
const elapsed = Date.now() - started;performance.now(), covered later, is more precise than Date.now().
Work Inside a Loop Multiplies
Something cheap once becomes expensive run a million times.
Example
Example
javascript
function isSlow(n) {
let total = 0;
for (let i = 0; i < n; i++) {
total += Math.sqrt(i);
}
return total;
}
console.log(typeof isSlow(1000));The square root itself is fast; doing it a million times is what costs time.
Avoid Repeating Work That Never Changes
Moving unchanging work outside a loop is one of the cheapest wins there is.
Example
Example
javascript
const items = ["a", "b", "c"];
function withRepeatedWork() {
const results = [];
for (const item of items) {
const upper = "PREFIX-" + "STATIC".toUpperCase();
results.push(upper + item);
}
return results;
}
function withoutRepeatedWork() {
const prefix = "PREFIX-" + "STATIC".toUpperCase();
const results = [];
for (const item of items) {
results.push(prefix + item);
}
return results;
}
console.log(withRepeatedWork().join(",") === withoutRepeatedWork().join(","));Both give the same answer; only one repeats the work needlessly.
Array Method Choice Rarely Matters Most
Readable code with map and filter is rarely the bottleneck.
Reach for a manual loop only once measuring says it matters.
Example
Example
javascript
const numbers = [1, 2, 3, 4, 5];
const withMethods = numbers.filter(function (n) { return n % 2 === 0; }).map(function (n) { return n * 2; });
const withLoop = [];
for (const n of numbers) {
if (n % 2 === 0) {
withLoop.push(n * 2);
}
}
console.log(withMethods.join(",") === withLoop.join(","));Both give 4,8, at almost identical cost for ordinary sizes.
The Right Data Structure Matters More
Choosing Set over array for membership checks is a far bigger win than micro-tweaks.
Example
Example
javascript
const allowedArray = ["a", "b", "c"];
const allowedSet = new Set(allowedArray);
console.log(allowedArray.includes("b"));
console.log(allowedSet.has("b"));Both give the same answer; the Set version stays fast as the list grows.
Do Not Optimise Blindly
Rewriting clear code into something clever, without measuring first, often helps nothing.
It also makes the code harder for the next person to read.
Example
Example
javascript
function clear(numbers) {
return numbers.reduce(function (sum, n) { return sum + n; }, 0);
}
console.log(clear([1, 2, 3, 4]));Keep it simple until measuring proves a specific line needs to change.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Performance Basics</title>
</head>
<body>
<h1>Performance Basics</h1>
<p id="out"></p>
<script>
const started = Date.now();
let total = 0;
for (let i = 0; i < 500000; i++) {
total += i;
}
const elapsed = Date.now() - started;
document.getElementById("out").textContent =
"Summed " + total + " in " + elapsed + "ms";
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try a bigger loop:
Raise the count and watch the elapsed time grow.
Important Points
- Measure before optimising; intuition is often wrong.
- Work inside a loop is what actually costs time.
- Moving unchanging work outside a loop is a cheap, safe win.
- The right data structure usually beats micro-optimising a loop.
- Do not sacrifice readability without proof it was needed.
Conclusion
Performance work starts with evidence, not assumptions.
The techniques in the rest of this section are tools, not defaults to reach for everywhere.
Use them where measuring shows they are actually needed.
