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

相关推荐
小码编匠1 小时前
C# 实现西门子S7系列 PLC 数据管理工具
后端·c#·.net
我不会编程55521 小时前
Python Cookbook-5.1 对字典排序
开发语言·数据结构·python
李少兄21 小时前
Unirest:优雅的Java HTTP客户端库
java·开发语言·http
无名之逆21 小时前
Rust 开发提效神器:lombok-macros 宏库
服务器·开发语言·前端·数据库·后端·python·rust
似水এ᭄往昔1 天前
【C语言】文件操作
c语言·开发语言
啊喜拔牙1 天前
1. hadoop 集群的常用命令
java·大数据·开发语言·python·scala
xixixin_1 天前
为什么 js 对象中引用本地图片需要写 require 或 import
开发语言·前端·javascript
W_chuanqi1 天前
安装 Microsoft Visual C++ Build Tools
开发语言·c++·microsoft
anlogic1 天前
Java基础 4.3
java·开发语言
A旧城以西1 天前
数据结构(JAVA)单向,双向链表
java·开发语言·数据结构·学习·链表·intellij-idea·idea