Reduce garbage collection pressure and improve application performance by avoiding unnecessary memory allocations. This significantly impacts overall system responsiveness, especially for high-throughput services.
Reduce garbage collection pressure and improve application performance by avoiding unnecessary memory allocations. This significantly impacts overall system responsiveness, especially for high-throughput services.
Key practices to follow:
// Instead of this (creates allocations):
var binaryData = ModelReaderWriter.Write(model);
return RequestContent.Create(binaryData);
// Use this (leverages shared buffers):
return BinaryContent.Create(model); // Uses UnsafeBufferSequence internally
// Instead of this (allocates new array):
json.WriteString("certificate", Convert.ToBase64String(data.ToArray()));
// Use this (avoids allocation):
json.WriteString("certificate", Convert.ToBase64String(data.Span));
// Cache agent tools to avoid API calls on every request
if (_agentTools is null)
{
PersistentAgent agent = await _client.Administration.GetAgentAsync(_agentId);
_agentTools = agent.Tools;
}
// Instead of loading the whole stream:
var allProfile = BinaryData.FromStream(stream).ToObjectFromJson<Dictionary<string, Dictionary<string, object>>>();
// Use streaming deserialization:
var allProfile = await JsonSerializer.DeserializeAsync<Dictionary<string, Dictionary<string, JsonElement>>>(stream, options);
These optimizations are particularly important in high-throughput scenarios where allocation pressure can cause frequent garbage collections, leading to performance degradation.
Enter the URL of a public GitHub repository