Properties vs fields in C Sharp (C#) - Performance Comparison
We want to see how fast code runs when using properties compared to fields in C#.
How does accessing or setting values change as we do it more times?
Analyze the time complexity of the following code snippet.
public class Sample
{
private int _field;
public int Property { get; set; }
public void UpdateValues(int n)
{
for (int i = 0; i < n; i++)
{
_field = i;
Property = i;
}
}
}
This code sets a private field and a public property inside a loop that runs n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Assigning values to a field and a property inside a loop.
- How many times: The loop runs n times, so these assignments happen n times.
Each time we increase n, the number of assignments grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 assignments (10 to field + 10 to property) |
| 100 | 200 assignments |
| 1000 | 2000 assignments |
Pattern observation: The total work grows directly with n, doubling because of two assignments per loop.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of loop runs increases.
[X] Wrong: "Accessing a property is always slower and changes the time complexity compared to a field."
[OK] Correct: Both field and property assignments happen once per loop iteration, so time grows linearly for both. The difference is tiny and does not change the overall growth pattern.
Understanding how properties and fields behave in loops helps you explain performance clearly and shows you know how code runs as it scales.
"What if the property had extra logic inside its setter? How would that affect the time complexity?"