.net通用垃圾收集优化技术

Avoid unnecessary allocations in hot paths

For example, in a tight loop or frequently called method, try to avoid creating new objects.

Bad:

csharp 复制代码
for(int i = 0; i < 100; i++) {
  var obj = new MyObject();
  //...
}

Good:

csharp 复制代码
MyObject obj = null;
for(int i = 0; i < 100; i++) {
  if(obj == null) {
    obj = new MyObject(); 
  }
  // Reuse obj instead of reallocating
}

Reuse buffers instead of allocating new ones

Avoid unnecessary allocations in hot paths

Reuse buffers instead of allocating new ones

For byte arrays or other buffers, allocate once and reuse instead of reallocating.

Bad:

csharp 复制代码
byte[] buffer = new byte[1024];

void ProcessData() {
  buffer = new byte[data.Length]; // re-allocate each time
  //...
}

Good:

csharp 复制代码
byte[] buffer = new byte[1024];

void ProcessData() {
  if(buffer.Length < data.Length) {
    // Resize only if needed
    buffer = new byte[data.Length]; 
  }

  // Reuse buffer
  //...
}

Use structs instead of classes where possible

Use structs instead of classes where possible

Structs can avoid heap allocations.

Bad:

csharp 复制代码
class Data {
  public int x;
  public int y;
}

Data data = new Data(); // allocated on heap

Good:

csharp 复制代码
struct Data {
   public int x;
   public int y; 
}

Data data; // allocated on stack

Here are some examples to illustrate those general garbage collection optimization techniques:

相关推荐
忒可君20 分钟前
C# winform FTP功能
开发语言·windows·c#
minji...1 小时前
C++ string类(STL简介 , string类 , 访问修改字符)
开发语言·c++
Forward♞1 小时前
Qt——文件操作
开发语言·c++·qt
老虎06272 小时前
JavaWeb前端02(JavaScript)
开发语言·前端·javascript
时光追逐者2 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
c#·.net·.netcore·.net core
Python私教2 小时前
YggJS RLogin暗黑霓虹主题登录注册页面 版本:v0.1.1
开发语言·javascript·ecmascript
carver w2 小时前
MFC,C++,海康SDK,回调,轮询
开发语言·c++·mfc
王廷胡_白嫖帝3 小时前
Qt猜数字游戏项目开发教程 - 从零开始构建趣味小游戏
开发语言·qt·游戏
XH华3 小时前
C语言第九章字符函数和字符串函数
c语言·开发语言