Fresh object literals vs variable assignment behavior in Typescript - Performance Comparison
Let's explore how creating new objects or assigning variables affects the time it takes for a program to run.
We want to know how the number of operations changes when we use fresh object literals versus reusing variables.
Analyze the time complexity of the following code snippet.
function createObjects(n: number) {
const arr = [];
for (let i = 0; i < n; i++) {
const obj = { value: i };
arr.push(obj);
}
return arr;
}
This code creates an array of n fresh objects, each with a property value set to the loop index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new object literal inside the loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each time we increase n, the loop runs more times, creating more objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The number of operations grows directly with n. Double the input, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size increases.
[X] Wrong: "Assigning the same object variable multiple times is just as slow as creating new objects each time."
[OK] Correct: Reusing the same object variable does not create new objects, so it does less work. Creating fresh objects inside a loop takes more time because each object is new and separate.
Understanding how object creation inside loops affects performance helps you write clearer and more efficient code, a skill valued in many coding challenges and real projects.
What if we moved the object literal outside the loop and reused it? How would the time complexity change?