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

Why records were introduced in C Sharp (C#) - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why records were introduced
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of properties grows, the number of comparisons grows too.

Input Size (number of properties)Approx. Operations (comparisons)
22
1010
100100

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

Final Time Complexity

Time Complexity: O(n)

This means comparing two records or classes takes time proportional to how many properties they have.

Common Mistake

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

Interview Connect

Understanding how records handle equality helps you explain design choices and performance trade-offs clearly in interviews.

Self-Check

What if we added nested records as properties? How would the time complexity of equality checks change?