Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences in StreamContent and ByteArrayContent webApi

I have searched all over the web, but not able to find the answer. We have two methods in our application:

a) First one return HttpResponseMessage with 1 file inside. It uses StreamContent.

 response.Content = new StreamContent(memStream);
 response.Content.Headers.ContentLength = memStream.Length;

b) Second one return HttpResponseMessage including zipp-ed files (multiple files that are zipped). it uses ByteArrayContent.

response.Content = new ByteArrayContent(memStream.ToArray());
response.Content.Headers.ContentLength = memStream.ToArray().Length;

I just wanted to understand why in our application StreamContent is used when returning just one file and ByteArrayContent is used when returning zip-ed file. Is there some logic there or not and I can change to use the same way in both situations?

like image 649
renathy Avatar asked Oct 14 '16 13:10

renathy


People also ask

What is Bytearraycontent?

Serializes the HTTP content into a stream of bytes and copies it to stream . (Inherited from HttpContent) CopyToAsync(Stream) Serialize the HTTP content into a stream of bytes and copies it to the stream object provided as the stream parameter.

What is StreamContent in c#?

StreamContent is the Content of a Stream, look for Stream.


1 Answers

Without anything to back up my assumption other than hearsay, streams are supposed to be more efficient than byte arrays (they basically work with smaller buffers of bytes at a time).

In the case of a web app, I believe streaming becomes even more efficient as it allows the consumer to actually download the page in pieces as it becomes available, rather than wait for all of the content to become ready in memory.

But it looks like your app is using a MemoryStream in both cases, and so practically speaking it might not make much of a difference (because the memory stream is a wrapper around a byte array...in memory). It is however calling memStream.ToArray() twice, which is less efficient as it copies its internal buffer to a new array a second time just to get its length (which you can call directly with memStream.Length.

Of course, without knowing what the rest of the app is doing, maybe there's a reason for it to marshal all of the zipped data before providing it.

like image 175
drzaus Avatar answered Sep 16 '22 20:09

drzaus