0
0
Javascriptprogramming~5 mins

Sequential vs parallel execution in Javascript - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Sequential vs parallel execution
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 tasks run one after another or all at once
100100 tasks run one after another or all at once
10001000 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"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?"