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

相关推荐
不吃香菜学java5 小时前
Redis的java客户端
java·开发语言·spring boot·redis·缓存
贵沫末6 小时前
python——打包自己的库并安装
开发语言·windows·python
文祐6 小时前
C++类之虚函数表及其内存布局(一个子类继承一个父类)
开发语言·c++
zuowei28896 小时前
华为网络设备配置文件备份与恢复(上传、下载、导出,导入)
开发语言·华为·php
xiaohe077 小时前
超详细 Python 爬虫指南
开发语言·爬虫·python
嗑嗑嗑瓜子的猫7 小时前
Java!它值得!
java·开发语言
xiaoshuaishuai87 小时前
C# GPU算力与管理
开发语言·windows·c#
lsx2024067 小时前
SVN 创建版本库
开发语言
xiaotao1317 小时前
01-编程基础与数学基石:Python错误与异常处理
开发语言·人工智能·python
皮卡蛋炒饭.8 小时前
线程的概念和控制
java·开发语言·jvm