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

相关推荐
only-qi1 分钟前
Java 包装器模式:告别“类爆炸“
java·开发语言
Yweir2 分钟前
Java 接口测试框架 Restassured
java·开发语言
郝学胜-神的一滴13 分钟前
Effective Modern C++ 条款39:一次事件通信的优雅解决方案
开发语言·数据结构·c++·算法·多线程·并发
香芋Yu15 分钟前
【从零构建AI Code终端系统】02 -- Bash 工具:一切能力的基础
开发语言·bash·agent·claude
专注VB编程开发20年16 分钟前
c#,vb.net Redis vs ODBC/ADO 查库的速度差距,写入json数据和字典数据
redis·c#·.net
码云数智-园园17 分钟前
Java Swing 界面美化与 JPanel 优化完全指南:从复古到现代的视觉革命
java·开发语言
@atweiwei17 分钟前
Rust 实现 LangChain
开发语言·算法·rust·langchain·llm·agent·rag
舟舟亢亢17 分钟前
Java并发编程(下)
java·开发语言
Дерек的学习记录18 分钟前
C++:类和对象part2
c语言·开发语言·c++·学习
我是大猴子19 分钟前
常见八股caffine
java·开发语言·mybatis