.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 小时前
19-AIAgent智能代理开发
微服务·.net
大傻^20 小时前
SpringAI2.0 Null Safety 实战:JSpecify 注解体系与 Kotlin 互操作
android·开发语言·人工智能·kotlin·springai
魑魅魍魉都是鬼20 小时前
Java 适配器模式(Adapter Pattern)
java·开发语言·适配器模式
笨笨马甲20 小时前
Qt MQTT
开发语言·qt
Fairy要carry21 小时前
面试-Agent上下文过载、步骤混乱的问题
开发语言·python
程序员Ctrl喵21 小时前
异步编程:Event Loop 与 Isolate 的深层博弈
开发语言·flutter
liuyao_xianhui21 小时前
优选算法_两数之和_位运算_C++
java·开发语言·数据结构·c++·算法·链表·动态规划
IT猿手21 小时前
MATLAB模拟四旋翼无人机飞行,机翼可独立旋转
开发语言·matlab·无人机
代龙涛21 小时前
WordPress 主题开发指南:模板文件、函数与页面选型规则
开发语言·后端·php·wordpress
代码探秘者21 小时前
【大模型应用】6.RAG 场景下的向量+关键词混合检索
java·开发语言·人工智能·python·spring