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

相关推荐
Java手札19 分钟前
Windows下Golang与Nuxt项目宝塔部署指南
开发语言·windows·golang
小生凡一22 分钟前
腾讯二面:TCC分布式事务 | 图解TCC|用Go语言实现一个TCC
开发语言·分布式·golang
minji...26 分钟前
C语言 函数递归
c语言·开发语言·算法
云上空1 小时前
C#初级知识总结
开发语言·c#
钢铁男儿1 小时前
C# 深入理解类:面向对象编程的核心数据结构
开发语言·数据结构·c#
Doker 多克2 小时前
Python-Django系列—部件
开发语言·python
江沉晚呤时2 小时前
深入解析 ASP.NET Core 中的 ResourceFilter
开发语言·c#·.net·lucene
huangyuchi.2 小时前
【C++11】Lambda表达式
开发语言·c++·笔记·c++11·lambda·lambda表达式·捕捉列表
XiaoyuEr_66882 小时前
如何创建一个C#项目(基于VS2022版)
开发语言·c#
Mercury-circle3 小时前
JavaScript基础知识合集笔记1——数据类型
开发语言·javascript·笔记