.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:

相关推荐
BUG研究员_10 小时前
Runnable与LCEL
开发语言·人工智能·python
牛艺翔12 小时前
C++基础
开发语言·c++
键盘会跳舞12 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
美味蛋炒饭.12 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
我星期八休息13 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
问商十三载13 小时前
RAG 检索效果差怎么排查?2026 五层诊断法完整指南
开发语言·人工智能·windows·python·算法
不负岁月无痕13 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
SomeB1oody13 小时前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程
萧瑟其中~13 小时前
多线程锁详解:互斥锁·自旋锁·读写锁(CAS + futex 原理)
开发语言·c++
qq_4480111613 小时前
C语言中的指针函数和函数指针
java·c语言·开发语言