Why modules are used in Javascript - Performance Analysis
We want to understand how using modules affects the time it takes for JavaScript code to run.
Specifically, we ask: does splitting code into modules change how fast it executes?
Analyze the time complexity of the following code snippet.
// main.js
import { greet } from './greet.js';
function run() {
for (let i = 0; i < 5; i++) {
greet(i);
}
}
run();
// greet.js
export function greet(num) {
console.log(`Hello number ${num}`);
}
This code imports a function from another file and calls it multiple times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop in
run()callsgreet()5 times. - How many times: Exactly 5 times, once per loop cycle.
Imagine changing the loop count to different sizes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to greet() |
| 100 | 100 calls to greet() |
| 1000 | 1000 calls to greet() |
As the number of calls grows, the total work grows in the same way, directly with n.
Time Complexity: O(n)
This means the time to run grows directly with how many times we call the function.
[X] Wrong: "Using modules makes the code slower because it adds extra steps."
[OK] Correct: Modules organize code but do not add extra loops or repeated work during execution. The main time cost depends on how many times functions run, not on splitting code into files.
Understanding how modules affect code helps you explain clean code design without worrying about slowing down programs. This skill shows you think about both structure and performance.
"What if the greet function itself contained a loop that runs n times? How would that change the time complexity?"