Synchronous vs asynchronous execution in Javascript - Performance Comparison
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?
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 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.
As n grows, the number of times the loop runs grows the same way whether synchronous or asynchronous.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
Pattern observation: The work inside the loop grows directly with n, no matter when it runs.
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.
[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.
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.
"What if we changed the asynchronous delay from 0 to 1000 milliseconds? How would the time complexity change?"