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

相关推荐
星释几秒前
Rust 练习册 4:Deref trait 与智能指针
开发语言·后端·rust
心随雨下3 分钟前
Java中将System.out内容写入Tomcat日志
java·开发语言·tomcat
小码编匠16 分钟前
WPF 绘制图表合集-LiveCharts
后端·c#·.net
AI视觉网奇26 分钟前
yolo 获取异常样本 yolo 异常
开发语言·python·yolo
散峰而望28 分钟前
C++入门(二) (算法竞赛)
开发语言·c++·算法·github
沐知全栈开发44 分钟前
CSS Float(浮动)详解
开发语言
Cx330❀1 小时前
《C++ 搜索二叉树》深入理解 C++ 搜索二叉树:特性、实现与应用
java·开发语言·数据结构·c++·算法·面试
阿猿收手吧!1 小时前
【C语言】localtime和localtime_r;strftime和strftime_l
linux·c语言·开发语言
不染尘.1 小时前
2025_11_5_刷题
开发语言·c++·vscode·算法·贪心算法·动态规划
不穿格子的程序员1 小时前
从零开始刷算法-栈-字符串解码
java·开发语言