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

相关推荐
踩着两条虫7 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB7 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
即使再小的船也能远航7 小时前
【Python】安装
开发语言·python
Irissgwe7 小时前
类与对象(三)
开发语言·c++·类和对象·友元
雪度娃娃8 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
萌新小码农‍9 小时前
python装饰器
开发语言·前端·python
KK溜了溜了9 小时前
Python从入门到精通
服务器·开发语言·python
故事和你919 小时前
洛谷-【图论2-1】树5
开发语言·数据结构·c++·算法·动态规划·图论
threelab9 小时前
Three.js 初中数学函数可视化 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
rockey6279 小时前
AScript如何实现LINQ语法
sql·c#·.net·linq·script·eval·expression