C# Struct vs Class: Key Differences 🔑 | 您所在的位置:网站首页 › structd › C# Struct vs Class: Key Differences 🔑 |
Structs are faster than classes when storing small amounts of data (under 16 bytes). It's because of the way they allocate memory: Classes are allocated on the heap and garbage-collected. Structs are allocated on the stack or inline and deallocated when the stack unwinds or the containing type is deallocated.Structs being stored on stack means cheaper allocations and deallocations than classes. However, classes may be faster than structs when working with large objects or when the object needs to be frequently boxed and unboxed. When we box a value, it creates a new object on the heap and copies the value into it. The new allocation might lead to performance degradation. So if you decide to use structs, pay attention to boxing. Use ref's to improve performanceTo improve the performance of structs we can pass them by reference using the ref keyword. That way, when we pass a struct to a method, we pass a reference rather than a copy. |
CopyRight 2018-2019 实验室设备网 版权所有 |