0
0
Typescriptprogramming~5 mins

Fresh object literals vs variable assignment behavior in Typescript - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Fresh object literals vs variable assignment behavior
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a new object literal inside the loop.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each time we increase n, the loop runs more times, creating more objects.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: The number of operations grows directly with n. Double the input, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input size increases.

Common Mistake

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

Interview Connect

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.

Self-Check

What if we moved the object literal outside the loop and reused it? How would the time complexity change?