With expressions for immutable copies in C Sharp (C#) - Time & Space 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?
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 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.
As the number of properties in the record grows, the time to create a copy grows proportionally.
| Input Size (number of properties) | Approx. Operations |
|---|---|
| 3 | 3 property copies |
| 10 | 10 property copies |
| 100 | 100 property copies |
Pattern observation: The time grows linearly with the number of properties copied.
Time Complexity: O(n)
This means the time to create a copy grows in direct proportion to the number of properties in the object.
[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.
Understanding how copying objects scales helps you write efficient code and explain your choices clearly in interviews.
"What if the record contains nested records or collections? How would the time complexity change?"