Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpResponseMessage.Content.ReadAsStreamAsync() vs HttpResponseMessage.Content.ReadAsStringAsync()

var request = new HttpRequestMessage(HttpMethod.Get, $"api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

using (var response = await _httpClient.SendAsync(request))
{
   response.EnsureSuccessStatusCode();
   var stream = await response.Content.ReadAsStreamAsync();        

     using (var streamReader = new StreamReader(stream))
     {
       using (var jsonTextReader = new JsonTextReader(streamReader))
       {
         var jsonSerializer = new JsonSerializer();
         var data =  jsonSerializer.Deserialize<Item>(jsonTextReader);
       }
     }
}

...

var request = new HttpRequestMessage(HttpMethod.Get, "api/Items");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.SendAsync(request);

response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Item>>(content);

I've run this two examples and I'm curious what is the difference between them that always getting same result, ReadAsStreamAsync is much faster then ReadAsStringAsync.

like image 301
west Avatar asked Jun 24 '20 20:06

west


People also ask

What does ReadAsStreamAsync do?

ReadAsStreamAsync()Serialize the HTTP content and return a stream that represents the content as an asynchronous operation.

What is ReadAsStringAsync C#?

ReadAsStringAsync() Serialize the HTTP content to a string as an asynchronous operation. ReadAsStringAsync(CancellationToken) Serialize the HTTP content to a string as an asynchronous operation.


2 Answers

Under the hood, HttpClient stores content in MemoryStream. So, basically calling ReadAsStreamAsync just returns a reference to the stream. In the case of calling ReadAsStringAsync, ToArray method is called on memory stream so an additional copy of data is created.

like image 59
DarkFinger Avatar answered Oct 15 '22 11:10

DarkFinger


You can check description for ReadAsStreamAsync and for ReadAsStringAsync

In few words - you can send to request content not only string. And ReadAsStreamAsync is only way for you here. If your response content is string - you can use both. But Stream is faster in Any Time.

This gives good explanation about memory allocation and perfomanse in these cases.

like image 41
Vladislav Avatar answered Oct 15 '22 11:10

Vladislav