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: