Sequential vs parallel execution in Javascript - Performance Comparison
When running tasks one after another or at the same time, the total time changes. We want to see how the time grows as we add more tasks.
How does doing things in order compare to doing them together?
Analyze the time complexity of the following code snippet.
// Sequential execution
async function runSequential(tasks) {
for (const task of tasks) {
await task();
}
}
// Parallel execution
async function runParallel(tasks) {
await Promise.all(tasks.map(task => task()));
}
This code runs a list of tasks either one by one or all at once.
- Primary operation: Calling each task function once.
- How many times: Exactly once per task, total of n tasks.
- Sequential uses a loop with await inside, waiting for each task before next.
- Parallel starts all tasks at once, waiting for all to finish together.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 tasks run one after another or all at once |
| 100 | 100 tasks run one after another or all at once |
| 1000 | 1000 tasks run one after another or all at once |
In sequential, total time adds up for each task. In parallel, total time is about the longest single task time, not the sum.
Time Complexity: O(n)
This means the total time grows linearly with the number of tasks when running sequentially. Parallel execution can be faster but still involves starting all tasks once.
[X] Wrong: "Running tasks in parallel always takes the same time as one task."
[OK] Correct: Even in parallel, the total time depends on the longest task, so if one task is slow, it slows down the whole batch.
Understanding how tasks run one by one or together helps you explain real-world code performance. It shows you can think about how programs handle many jobs efficiently.
"What if tasks had different lengths and we ran them in batches of 5 instead of all at once? How would the time complexity change?"
Practice
What is the main difference between sequential and parallel execution in JavaScript?
Solution
Step 1: Understand sequential execution
Sequential execution means tasks run one by one, waiting for each to finish before starting the next.Step 2: Understand parallel execution
Parallel execution means tasks run at the same time, so they can finish faster by overlapping.Final Answer:
Sequential runs tasks one after another; parallel runs tasks at the same time. -> Option BQuick Check:
Sequential = one by one, Parallel = at the same time [OK]
- Confusing which runs tasks simultaneously
- Thinking sequential is always faster
- Mixing up async/await with execution type
Which of the following is the correct syntax to run two promises in parallel using Promise.all?
const p1 = fetch(url1); const p2 = fetch(url2); // What is correct?
Solution
Step 1: Identify correct Promise method for parallel
Promise.all runs multiple promises in parallel and waits for all to finish.Step 2: Check syntax correctness
Using await Promise.all([p1, p2]) correctly waits for both promises in parallel.Final Answer:
const results = await Promise.all([p1, p2]); -> Option DQuick Check:
Promise.all = parallel wait [OK]
- Using Promise.race which waits only for first promise
- Using non-existent Promise.sequence or Promise.parallel
- Not wrapping promises in an array
What will be the output of this code?
async function test() {
console.log('Start');
await new Promise(r => setTimeout(r, 1000));
console.log('Middle');
await new Promise(r => setTimeout(r, 1000));
console.log('End');
}
test();Solution
Step 1: Analyze first await delay
After printing 'Start', the code waits 1 second before printing 'Middle'.Step 2: Analyze second await delay
After 'Middle', it waits another 1 second before printing 'End'.Final Answer:
Start immediately, then Middle after 1s, then End after 2s -> Option AQuick Check:
await pauses sequentially, so output is delayed stepwise [OK]
- Thinking all logs print immediately
- Confusing setTimeout with immediate execution
- Ignoring await pauses
Find the error in this code that tries to run two async tasks in parallel:
async function runTasks() {
const result1 = await task1();
const result2 = await task2();
return [result1, result2];
}Solution
Step 1: Check how tasks are awaited
Each await waits for task1 to finish before starting task2, so tasks run one after another.Step 2: Identify parallel execution fix
To run in parallel, start both tasks without await, then await both together using Promise.all.Final Answer:
Tasks run sequentially, not in parallel. -> Option CQuick Check:
Separate awaits cause sequential execution [OK]
- Assuming await runs tasks in parallel
- Thinking async keyword fixes parallelism alone
- Believing async functions can't return arrays
You want to fetch data from three URLs and process results only after all are done. Which code correctly runs fetches in parallel and waits for all?
const urls = ['url1', 'url2', 'url3'];
async function fetchAll() {
// Fill this
}Solution
Step 1: Understand parallel fetch with Promise.all
Using Promise.all with map starts all fetches at once and waits for all to finish.Step 2: Check other options for errors
const results = []; for (const url of urls) { results.push(await fetch(url)); } fetches sequentially due to await inside loop; const results = urls.map(url => await fetch(url)); uses await incorrectly inside map; const results = await urls.forEach(url => fetch(url)); misuses forEach which returns undefined.Final Answer:
const results = await Promise.all(urls.map(url => fetch(url))); -> Option AQuick Check:
Promise.all + map = parallel fetch [OK]
- Await inside for loop causing sequential fetch
- Using await inside map callback directly
- Using forEach which does not return promises
Ready to prove it?
Pass the test and this pattern moves unknown
