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

相关推荐
我是鶸10 分钟前
secml-malware python library 源码分析及实践
开发语言·python
setmoon21416 分钟前
C++代码规范化工具
开发语言·c++·算法
不想看见40417 分钟前
C++/Qt 代码规范指南
开发语言·qt
li星野33 分钟前
QT模拟题:QT项目实践与架构设计(120分钟)
开发语言·qt
大鹏说大话1 小时前
Java 锁膨胀机制深度解析:从偏向锁到重量级锁的进化之路
开发语言·c#
IT猿手1 小时前
基于 ZOH 离散化与增量 PID 的四旋翼无人机轨迹跟踪控制研究,MATLAB代码
开发语言·算法·matlab·无人机·动态路径规划·openclaw
IT猿手1 小时前
基于控制障碍函数(Control Barrier Function, CBF)的无人机编队三维动态避障路径规划,MATLAB代码
开发语言·matlab·无人机·动态路径规划·无人机编队
huaweichenai1 小时前
java的时间操作介绍
java·开发语言
就不掉头发1 小时前
C++右值与右值引用
开发语言·c++
IT猿手1 小时前
基于 CBF 的多无人机编队动态避障路径规划研究,无人机及障碍物数量可以自定义修改,MATLAB代码
开发语言·matlab·无人机·动态路径规划