Why records were introduced in C Sharp (C#) - Performance Analysis
We want to understand how using records affects the time it takes for certain operations in C# programs.
Specifically, we ask: how does the design of records impact performance compared to classes?
Analyze the time complexity of comparing two record instances versus two class instances.
public record PersonRecord(string Name, int Age);
public class PersonClass
{
public string Name { get; init; }
public int Age { get; init; }
public override bool Equals(object? obj)
{
if (obj is not PersonClass other) return false;
return Name == other.Name && Age == other.Age;
}
}
// Comparing two instances
var r1 = new PersonRecord("Alice", 30);
var r2 = new PersonRecord("Alice", 30);
bool areEqualRecords = r1 == r2;
var c1 = new PersonClass { Name = "Alice", Age = 30 };
var c2 = new PersonClass { Name = "Alice", Age = 30 };
bool areEqualClasses = c1.Equals(c2);
This code shows how records automatically provide value-based equality, while classes need manual code.
Look at what happens when comparing two objects.
- Primary operation: Comparing each property for equality.
- How many times: Once per property in the record or class.
As the number of properties grows, the number of comparisons grows too.
| Input Size (number of properties) | Approx. Operations (comparisons) |
|---|---|
| 2 | 2 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The time to compare grows linearly with the number of properties.
Time Complexity: O(n)
This means comparing two records or classes takes time proportional to how many properties they have.
[X] Wrong: "Records are always faster than classes because they are new."
[OK] Correct: Records simplify code and provide built-in equality, but the time to compare depends on the number of properties, not the type itself.
Understanding how records handle equality helps you explain design choices and performance trade-offs clearly in interviews.
What if we added nested records as properties? How would the time complexity of equality checks change?