Reduce Memory Overhead
Traditional Approach – ReadAsStringAsync
I have seen many developers reading data from String by calling ReadAsStringAsync. The downside of this approach is it creates unnecessary strings objects. If the JSON size is 5 MB then it will create lots of string objects in the memory.
HttpResponseMessage response = await client.GetAsync ("https://jsonplaceholder.typicode.com/posts");
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync ();
Items = JsonSerializer.Deserialize<List<TodoItem>>(content, serializerOptions);
}
Recommended Approach – ReadAsStreamAsync
The best approach is to read data directly from the stream instead of converting it to string objects. As you will notice in the below code we are using response.Content.ReadAsStreamAsync() method to get the response.
With this approach, you can reduce memory overhead. This approach is suitable for the following use cases
- When you are getting large JSON Response.
- When you are consuming api in a loop.
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts");
JsonSerializer jsonSerializer = new JsonSerializer();
using (var stream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
using (var json = new JsonTextReader(reader))
{
return jsonSerializer.Deserializer(json);
}