Module 22: Loops and Algorithms
Efficiency
🏠The everyday picture
Checking every guest's name against the list at a wedding of 50 people is fine. At a rally of 50,000, checking each person against every other person would take days. How work grows matters more than how fast one step is.
📘What it really is
- Efficiency is about how the work grows as the data grows, often written in Big O notation:
- O(1): the same work however big the data (a Map lookup);
- O(log n): grows very slowly (binary search);
- O(n): grows in step with the data (one loop over the list);
- O(n²): grows with the square: a loop inside a loop over the same list. 1,000 items means a million steps; 100,000 items means ten billion.
-
The common accident is a hidden loop inside a loop, such as calling
findorincludesinside amapover another large list. Fix it by building a Map or Set first. -
For a few hundred items, almost anything is fast enough. Write clear code first; speed it up when the data is big or something is measurably slow.
-
console.time("label")andconsole.timeEnd("label")measure how long code takes.
🖱️Try it
Make an array of 20,000 fake orders, each with a random productId from your products. Time looking up the
product name for every order, first with products.find(...) inside a map, then with a Map built beforehand.
Compare the times. (Ask an AI to help write the fake-data generator, and read what it gives you.)
✅Quick check
For each of 10,000 orders, code calls customers.find(...) over 10,000 customers. Roughly how many steps?
Show the answer
Up to 100 million (10,000 × 10,000). A Map of customers by id makes it about 10,000.
Should you always write the fastest possible code?
Show the answer
No. Write clear code first; optimise when the data is large or something is measurably slow.
