Data Structures & Big-O
Learn how to choose the right data structure for the job and understand Big-O notation to predict how your code will scale.
Scaling Your Code
When your application only handles 10 users, any code will run fast. But what happens when it needs to handle 10,000 users? Or 10 million?
**Big-O Notation** is a mathematical way to describe how the runtime of an algorithm grows as the size of the input (n) increases.
The Price of Inefficiency
If you choose the wrong data structure, a simple search feature could freeze the user's browser for several seconds.
Understanding Big-O helps you spot these performance bottlenecks *before* they reach production. It is the universal language developers use to discuss performance.
The Three Common Big-O Runtimes
**1. O(1) Constant Time:** Instant access. Looking up a key in a JavaScript Object or Map. It takes the exact same amount of time whether there are 10 items or 10 million.
javascript
const user = users['id_999']; // O(1) Instant
**2. O(n) Linear Time:** Proportional access. Looping through an Array with .find(). If the array is 100x larger, the search takes 100x longer.
javascript
const user = users.find(u => u.id === 'id_999'); // O(n) Scales linearly
**3. O(n²) Quadratic Time:** Exponential danger. A loop inside a loop (nested loops). If the array is 100x larger, the execution takes 10,000x longer. Avoid this for large datasets!
javascript
for(let i=0; i<users.length; i++) {
for(let j=0; j<users.length; j++) { ... }
} // O(n²) Danger!
The Big-O Race
Examine the growth curves below. Notice how O(1) remains perfectly flat, O(n) grows steadily, and O(n²) quickly explodes into the danger zone as the input size increases.
The Big-O Race
const user = usersMap['id_999'];
const user = usersArray.find(u => u.id === 'id_999');
for (let i=0; i<arr.length; i++) {
for (let j=0; j<arr.length; j++) {
// Execution explodes here!
}
}
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- **Big-O Notation** describes how runtime scales as the input size (
n) grows. - **O(1) Constant Time**: Instant access regardless of size (e.g., Object lookups,
Set.has()). - **O(n) Linear Time**: Runtime grows proportionally with size (e.g.,
Array.find(),Array.includes()). - **O(n²) Quadratic Time**: Runtime grows exponentially. Highly dangerous for large inputs (e.g., nested
forloops). - Never put an O(n) array search (like
.includes()) inside an existing loop; use aSetinstead for O(1) lookups.
Done with this concept?
Mark it complete to track your progress. No login needed.