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

相关推荐
牛奔8 小时前
Go 如何打印调试深层或嵌套的结构体
开发语言·后端·golang
geovindu8 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
学逆向的8 小时前
汇编——JCC指令
开发语言·汇编·网络安全
mayaairi9 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
kite012110 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
l1564694811 小时前
突围!图文混合知识库难以解析,Kimi-K3 原生视觉架构深耕知识工作,DMXAPI 统一接口,缩短项目开发周期
java·大数据·开发语言
charlie11451419112 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
IT小盘13 小时前
04-大模型流式输出原理-SSE与Python实现
开发语言·网络·人工智能·python
不如语冰13 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
阿童木写作14 小时前
Python批量翻译亚马逊商品图实战教程
开发语言·python·xcode