Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Strings vs. Streams - Memory Profile and Characteristics

Tags:

People also ask

What is the difference between stream and string?

Strings are arrays of characters used to hold data like "Hi I am a string." A Stream is an i/o class that is used to read and write bytes of data as a continuous sequence of bytes. You can use streams to read and write data from/to files, among other things.

What is the difference between memory stream and stream?

You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string.

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.

How is a string stored in memory C#?

String just implements an indexer of type char internally and we can say that string is just equivalent to char[] type with lots of extra code to make it useful for you, hence, like an array, it is stored on heap always.


I need to pull large Unicode textual strings (e.g. 200Mb) from a Database (nvarchar) and store in memory for processing. i.e. I need random access to all parts of the strings.

Looking at this from strictly memory centric point of view, what are the pro’s and con’s of using a System.IO.MemoryStream versus a System.String as my in memory representation.

Some factors I am trying to research are:

  • How these objects act in a [hypothetical] highly fragmented low memory environment
  • Immutability
  • Actual size in memory (if stream is UTF8, have we nearly halved size)
  • Is there another object I have not thought about?

I am looking for clarity and advice on these points, as well as any other memory considerations I have not thought of?

Note: There may be better way of processing these strings, but at this point I am realy just asking about the memory consideration of storing such an object.