C# memory knowledge

C# memory knowledge

C# is a programming language that produces intermediate language (IL) after compiling the C# source code. The CLR (Common Language Runtime) then loads this IL and executes it. So C# is a managed language, and its garbage collection mechanism (GC) is handled by the CLR. In addition, the C# language does not have pointers, so we rarely consider the memory usage and how the project is running during use. for memory management. However, C# is only hidden from programmers in terms of memory management, which does not mean that it does not involve these things, and even its internal management may be more complicated than its own management.

C# Object Classification

Objects in C# are divided into value types (value type) and reference types (reference type). For details, refer to the two types of data in C#: value types and reference types .

For value types, the variable directly stores its data (on the stack), while for reference types, the variable only stores the address (on the stack) at which the corresponding data can be found (if the value type is declared in the reference type as fields, they are stored inline on the heap).

C# Memory Mechanism - Basics

Memory allocation of C# structure

When interoperating with unmanaged code, it is sometimes necessary to pass structure parameters. Because there is a difference in memory allocation between the two, and to solve this difference, you must know the structure memory allocation and size in C#. Let's take a brief look at the relevant code as follows:

// 所有结构体均使用默认的特性
// StructLayoutAttribute 类使用户可以控制类或结构的数据字段的物理布局。
StructLayoutAttribute(Value = LayoutKind.Sequential, Pack = 8)

// 结构体实际大小计算使用
Marshal.SizeOf(typeof(StructName))

Then look at the example, the memory size occupied is also marked:

struct s1 // 32字节
{
    int x;    // 4 :0-3
    double b; // 8 :8-16 (由于剩余的不足8字节,所以这里的空间浪费了)
    double b; // 8 :17-24
    byte a;   // 1 :25 (根据字节对齐原则,后面7个字节留空)
}
struct s2 // 24字节
{
    byte a;   // 1 :0
    int x;    // 4 :1-4
    double b; // 8 :8-16 (浪费三个字节,从下一个对齐位置开始)
    double c; // 8 :17-24
}

It can be seen that there is a byte alignment problem. In the process of continuous allocation, less than 8 bytes are aligned to 8 bytes, if there is not enough left to store the next variable, it will be filled to 8 bytes, and the next 8 bytes will be saved.
If you can be sure that it will not be passed to the dll, but only used by the hosting environment, you don't need StructLayout (default auto), which may improve memory utilization. Because .net will adjust the layout of managed objects, such as in the example, the memory utilization rate has been improved after adjusting the order.

Guess you like

Origin blog.csdn.net/qq_36433883/article/details/126702194