0
0
Javascriptprogramming~5 mins

Synchronous vs asynchronous execution in Javascript - Performance Comparison

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

We want to see how the order of running code affects how long it takes. This helps us understand how tasks that wait or run later change the work done.

How does running code one after another compare to running some parts later?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function syncTask(n) {
  for (let i = 0; i < n; i++) {
    console.log(i);
  }
}

function asyncTask(n) {
  setTimeout(() => {
    for (let i = 0; i < n; i++) {
      console.log(i);
    }
  }, 0);
}
    

This code shows a loop running immediately (synchronous) and the same loop running after a short delay (asynchronous).

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that runs from 0 to n-1.
  • How many times: Exactly n times in both synchronous and asynchronous versions.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way whether synchronous or asynchronous.

Input Size (n)Approx. Operations
1010 loop steps
100100 loop steps
10001000 loop steps

Pattern observation: The work inside the loop grows directly with n, no matter when it runs.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish the loop grows in a straight line with the size of n, whether the code runs now or later.

Common Mistake

[X] Wrong: "Asynchronous code always runs faster because it runs later."

[OK] Correct: The total work inside the loop is the same; asynchronous just delays when it runs, not how much work it does.

Interview Connect

Understanding how synchronous and asynchronous code affects timing helps you explain how programs handle tasks and wait times. This skill shows you know how code flow impacts performance.

Self-Check

"What if we changed the asynchronous delay from 0 to 1000 milliseconds? How would the time complexity change?"