Avoid unnecessary allocations in hot paths
For example, in a tight loop or frequently called method, try to avoid creating new objects.
Bad:
for(int i = 0; i < 100; i++) {
var obj = new MyObject();
//...
}
Good:
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:
byte[] buffer = new byte[1024];
void ProcessData() {
buffer = new byte[data.Length]; // re-allocate each time
//...
}
Good:
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:
class Data {
public int x;
public int y;
}
Data data = new Data(); // allocated on heap
Good:文章来源:https://www.toymoban.com/news/detail-736390.html
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:文章来源地址https://www.toymoban.com/news/detail-736390.html
到了这里,关于.net通用垃圾收集优化技术的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!