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

相关推荐
驭渊的小故事21 分钟前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
Sakura_j_h_1 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q1 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
Eider19982 小时前
Python基础语法之并发相关3
开发语言·python
FRing032 小时前
vue2干货总结11(短信验证、登录功能、统一处理错误(响应拦截器)、将token信息存入vuex、vuex持久化处理)
开发语言·前端·javascript·vue.js·vue2
风云3 小时前
从 NLite 到 Vane.Container 1.0:压箱十六年的自研 DI 容器开源
.net·di·mini 容器·nlite
CS_Zero3 小时前
DeepSeek V4.1 Flash 1017 (Batch) 新手极速上手指南
开发语言·batch·deepseek
山楂树の3 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
Risehuxyc3 小时前
C# 发展历史
开发语言·c#
七夜zippoe4 小时前
Nexent 知识库:调优靠 Chunk 与重排
开发语言·python·ai智能体·nexent·知识库与rag