Readonly structs in C Sharp (C#) - Time & Space Complexity
When working with readonly structs in C#, it's important to understand how their use affects the speed of your program.
We want to see how the time it takes to run code changes as the amount of data grows.
Analyze the time complexity of the following code snippet.
public readonly struct Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public int Distance() => X * X + Y * Y;
}
Point[] points = new Point[1000];
for (int i = 0; i < points.Length; i++)
{
points[i] = new Point(i, i);
}
int totalDistance = 0;
for (int i = 0; i < points.Length; i++)
{
totalDistance += points[i].Distance();
}
This code creates an array of readonly Point structs, initializes them, and then sums their distances.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two loops each running through the array of points.
- How many times: Each loop runs once for every point, so 1000 times if the array has 1000 points.
As the number of points grows, the time to run the loops grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (2 loops x 10) |
| 100 | About 200 operations (2 loops x 100) |
| 1000 | About 2000 operations (2 loops x 1000) |
Pattern observation: The total work grows directly with the number of points. Double the points, double the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the number of points.
[X] Wrong: "Using readonly structs makes the code run faster by reducing the time complexity."
[OK] Correct: Readonly structs help with safety and sometimes memory, but they don't change how many times the code runs through the data.
Understanding how readonly structs affect performance helps you write clear and efficient code, a skill valued in many programming tasks.
"What if we replaced the readonly struct with a class? How would the time complexity change?"