.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 小时前
Crypto、Cipher与Password:Java加密开发的三个核心概念
java·开发语言·python
非酋讨厌10 小时前
.NET 11 Preview 4 正式发布:Runtime-Async 全面启用、Process API 大幅扩展
.net
white_ant10 小时前
JDK LTS 版本升级迁移注意事项大全
java·开发语言
Bobolink_10 小时前
跨境业务网络环境评估,“干净、一致、独享”三个关键指标
开发语言·网络·php·跨境网络·网络环境
你怎么知道我是队长10 小时前
JavaScript的变量和数据类型介绍
开发语言·javascript·ecmascript
xingke10 小时前
C 语言多文件编程:(一)头文件、extern、编译链接
c语言·开发语言·多文件
戮漠summer11 小时前
Missing Semester 计算机教育中缺失的一课 Lecture 01 Shell
开发语言·后端·scala
jinyishu_11 小时前
C++ string使用方法
开发语言·c++
EW Frontier11 小时前
三级跳突破864维动作空间——QMIX-Hierarchical多无人机协同通信方法全解析【附python代码】
开发语言·python·无人机·强化学习·通信资源分配
名字还没想好☜11 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js