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

  1. When you are getting large JSON Response.
  2. 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);
}


4 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments