Click here to Skip to main content
15,030,355 members
Articles / Programming Languages / C#
Tip/Trick
Posted 25 Jul 2021

Tagged as

Stats

8.3K views
14 bookmarked

Prefer using Stream to byte[]

Rate me:
Please Sign up or sign in to vote.
5.00/5 (19 votes)
9 Aug 2021CPOL2 min read
A short example of how byte[] misuse may hurt memory consumption
While reviewing and refactoring a real-world codebase, I've noticed how byte[] API is misused. That is the reason why in this article I'm sharing some thoughts on why you shouldn't evade Stream API in your code.

Introduction

When working with files, there are often both APIs operating byte[] and Stream so quite often people chose byte[] counterpart as it requires less ceremony or just intuitively more clear.

You may think of this conclusion as far-fetched but I’ve decided to write about it after reviewing and refactoring some real-world production code. So you may find this simple trick neglected in your codebase as some other simple things I’ve mentioned in my previous articles.

Example

Let’s look at the example as simple as calculating file hash. In spite of its simplicity, some people believe that the only way to do it is to read the entire file into memory.

Experienced readers may have already foreseen a problem with such an approach. Let’s see do some benchmarking on 900MB file to see how the problem manifests and how we can circumvent it.

The baseline will be the naive solution of calculating hash from byte[] source:

C#
public static Guid ComputeHash(byte[] data)
{
    using HashAlgorithm algorithm = MD5.Create();
    byte[] bytes = algorithm.ComputeHash(data);
    return new Guid(bytes);
}

So following the advice from the title of the article, we’ll add another method that will accept Stream convert it to byte array and calculate hash.

C#
public async static Task<Guid> ComputeHash(Stream stream, CancellationToken token)
{
    var contents = await ConvertToBytes(stream, token);
    return ComputeHash(contents);
}

private static async Task<byte[]> ConvertToBytes(Stream stream, CancellationToken token)
{
    using var ms = new MemoryStream();
    await stream.CopyToAsync(ms, token);
    return ms.ToArray();
}

However, calculating hash from byte[] is not the only option. There’s also an overload that accepts Stream. Let’s use it.

C#
public static Guid ComputeStream(Stream stream)
{
    using HashAlgorithm algorithm = MD5.Create();
    byte[] bytes = algorithm.ComputeHash(stream);
    stream.Seek(0, SeekOrigin.Begin);
    return new Guid(bytes);
}

Results are quite telling:

Image 1

So what happened here? While we tried to blindly follow the advice in the article, it didn’t help. The key takeaway from these figures is that using Stream allows us to process files in chunks instead of loading them into memory naively. While you may not notice this on small files but as soon as you have to deal with large files loading them into memory at once becomes quite costly.

Most of .NET methods that work with byte[] already exhibit Stream counterpart so it shouldn’t be a problem to use it. When you provide your own API, you should consider supplying a method that operates with Stream in a robust batch-by-batch fashion.

Let’s use the following code checking two streams for equality as another example:

C#
private const int bufferSize = 2048;

public static bool IsEqual(this Stream stream, Stream otherStream)
{
    if (stream is null) return false;

    if (otherStream is null) return false;

    if (stream.Length != otherStream.Length) return false;

    if (stream == otherStream) return true;

    byte[] buffer = new byte[bufferSize];
    byte[] otherBuffer = new byte[bufferSize];

    while (stream.Read(buffer, 0, buffer.Length) > 0)
    {
        otherStream.Read(otherBuffer, 0, otherBuffer.Length);

        if (!otherBuffer.SequenceEqual(buffer))
        {
            stream.Seek(0, SeekOrigin.Begin);
            otherStream.Seek(0, SeekOrigin.Begin);
            return false;
        }
    }

    stream.Seek(0, SeekOrigin.Begin);
    otherStream.Seek(0, SeekOrigin.Begin);

    return true;
}

Here, instead of loading two potentially big files into memory, we compare them using chunks of 2KB. Once chunks are different, we exit.

Conclusion

Stream APIs allow batch-by-batch processing which allows us to reduce memory consumption on big files. While on a first glance, Stream API may seem as requiring more ceremony, it’s definitely a useful tool in one’s toolbox.

History

  • 25th July, 2021 - Published initial version
  • 9th August, 2021 - Updated stream comparison code according to comments

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Bohdan Stupak
Software Developer
Ukraine Ukraine
https://twitter.com/BohdanStupak1

Comments and Discussions

 
QuestionMeasurements Pin
Mobster_11-Aug-21 13:50
MemberMobster_11-Aug-21 13:50 
QuestionOne more advantage of Stream over byte[] is also on async situations Pin
Adérito Silva30-Jul-21 6:26
MemberAdérito Silva30-Jul-21 6:26 
AnswerRe: One more advantage of Stream over byte[] is also on async situations Pin
Bohdan Stupak9-Aug-21 2:56
professionalBohdan Stupak9-Aug-21 2:56 
QuestionChecking two streams, a couple of suggestions. Pin
George Swan27-Jul-21 20:28
MemberGeorge Swan27-Jul-21 20:28 
AnswerRe: Checking two streams, a couple of suggestions. Pin
Bohdan Stupak30-Jul-21 3:42
professionalBohdan Stupak30-Jul-21 3:42 
AnswerRe: Checking two streams, a couple of suggestions. Pin
Bohdan Stupak9-Aug-21 2:59
professionalBohdan Stupak9-Aug-21 2:59 
GeneralShould use array only when array size is known at design time. Pin
Adérito Silva25-Jul-21 6:22
MemberAdérito Silva25-Jul-21 6:22 
GeneralRe: Should use array only when array size is known at design time. Pin
Bohdan Stupak30-Jul-21 3:41
professionalBohdan Stupak30-Jul-21 3:41 
QuestionQuestion about the definition of "equal" Pin
Nelek25-Jul-21 0:56
protectorNelek25-Jul-21 0:56 
AnswerRe: Question about the definition of "equal" Pin
Bohdan Stupak25-Jul-21 1:17
professionalBohdan Stupak25-Jul-21 1:17 
GeneralRe: Question about the definition of "equal" Pin
Nelek25-Jul-21 8:44
protectorNelek25-Jul-21 8:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.