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

相关推荐
心.c12 分钟前
JavaScript单线程实现异步
开发语言·前端·javascript·ecmascript
awonw1 小时前
[python][基础]Flask 技术栈
开发语言·python·flask
木宇(记得热爱生活)1 小时前
Qt GUI缓存实现
开发语言·qt·缓存
lly2024061 小时前
C# 正则表达式
开发语言
Chef_Chen1 小时前
从0开始学习R语言--Day58--竞争风险模型
android·开发语言·kotlin
咖啡の猫2 小时前
bash的特性-常见的快捷键
开发语言·chrome·bash
命苦的孩子2 小时前
Java 中的排序算法详解
java·开发语言·排序算法
咖啡の猫2 小时前
bash的特性-常用的通配符
开发语言·chrome·bash
淮北4942 小时前
STL学习(四、队列和堆栈)
开发语言·c++·学习
惜.己2 小时前
pytest中使用ordering控制函数的执行顺序
开发语言·python·pytest