0
0
C Sharp (C#)programming~5 mins

With expressions for immutable copies in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: With expressions for immutable copies
O(n)
Understanding Time Complexity

We want to understand how the time it takes to create immutable copies using with expressions changes as the data size grows.

Specifically, how does copying an object with some changes affect performance when the object has many properties?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


record Person(string Name, int Age, string Address);

var original = new Person("Alice", 30, "123 Main St");
var copy = original with { Age = 31 };

This code creates a new immutable copy of a Person record, changing only the Age property.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Copying each property from the original object to the new one.
  • How many times: Once per property in the record.
How Execution Grows With Input

As the number of properties in the record grows, the time to create a copy grows proportionally.

Input Size (number of properties)Approx. Operations
33 property copies
1010 property copies
100100 property copies

Pattern observation: The time grows linearly with the number of properties copied.

Final Time Complexity

Time Complexity: O(n)

This means the time to create a copy grows in direct proportion to the number of properties in the object.

Common Mistake

[X] Wrong: "Creating a copy with a with expression is instant no matter how big the object is."

[OK] Correct: Each property must be copied to the new object, so more properties mean more work and more time.

Interview Connect

Understanding how copying objects scales helps you write efficient code and explain your choices clearly in interviews.

Self-Check

"What if the record contains nested records or collections? How would the time complexity change?"