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

相关推荐
好焊孙辉44 分钟前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言
布莱克6051 小时前
Swift 中的逃逸闭包与非逃逸闭包:@escaping 到底在做什么
开发语言·ios·swift·闭包·逃逸
郝学胜-神的一滴1 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
吃我一窝jio2 小时前
Java IO流核心分类与应用
java·开发语言·笔记
Kari113 小时前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
Jeff-Tsai5 小时前
Polhem.Chat:Avalonia 与 Blazor 的 AI 聊天组件
ai·.net·blazor·avalonia
布莱克6056 小时前
Swift 可选链详解:从语法到实战
开发语言·ios·swift·可选链
布莱克6057 小时前
Swift 类型转换详解:从基础语法到实战技巧
开发语言·ios·swift·类型转换
码途行者7 小时前
每天10分钟学Go:第23课 协程(goroutine)
开发语言·后端·golang
艾莉丝努力练剑8 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构