Understanding the speed difference between value types and reference types helps you write faster and more efficient C# programs.
Value type vs reference type performance in C Sharp (C#)
struct MyValueType {
public int Number;
}
class MyReferenceType {
public int Number;
}Value types store data directly and are usually faster for small data.
Reference types store a reference (like an address) to the data on the heap.
struct Point {
public int X;
public int Y;
}
Point p = new Point { X = 5, Y = 10 };class Person { public string Name; } Person person = new Person { Name = "Anna" };
This program shows how changing a copy of a value type does not affect the original, but changing a reference type copy affects the original because both point to the same data.
using System; struct MyValueType { public int Number; } class MyReferenceType { public int Number; } class Program { static void Main() { MyValueType val1 = new MyValueType { Number = 10 }; MyValueType val2 = val1; // copies the value val2.Number = 20; Console.WriteLine($"val1.Number = {val1.Number}"); Console.WriteLine($"val2.Number = {val2.Number}"); MyReferenceType ref1 = new MyReferenceType { Number = 10 }; MyReferenceType ref2 = ref1; // copies the reference ref2.Number = 20; Console.WriteLine($"ref1.Number = {ref1.Number}"); Console.WriteLine($"ref2.Number = {ref2.Number}"); } }
Value types are stored on the stack, which is faster to access.
Reference types are stored on the heap, which can be slower due to extra memory management.
Use value types for small, simple data to improve performance.
Value types hold data directly and are faster for small data.
Reference types hold a pointer to data and can be slower due to memory access.
Understanding this helps you choose the right type for better program speed.