Why Stream.Copy is faster than Stream.Write to FileStream?

Refresh

February 2019

Views

37 time

4

I have a question and I can't find a reason for it. I'm creating a custom archive file , I'm using Memory Streams to storing data and finally I use a file stream to write the data to disk.

My Hard Disk is SSD , But the speed was too slow when I tried to write only 95MB to a file , It takes 12 second to write !

I tried Filestream.Write and File.WriteAllBytes but Same!

At the end I got an idea to do it with copying and it was 100x faster !

I need to know why this is happening and what's wrong with write functions.

Here's my code :

//// First of all I create an example 150MB file
Random randomgen = new Random();
byte[] new_byte_array = new byte[150000000];
randomgen .NextBytes(new_byte_array);

//// I turned byte arrays to memorystream
MemoryStream file1 = new MemoryStream(new_byte_array);
//// HERE I DO SOMETHINGS WITH MEMORYSTREAM


/// Method 1 : File.WriteAllBytes | 13,944 ms
byte[] output = file1.ToArray();
File.WriteAllBytes("output.test", output);

// Method 2 : FileStream | 8,471 ms
byte[] output = file1.ToArray();
FileStream outfile = new FileStream("outputfile",FileMode.Create,FileAccess.ReadWrite);
outfile.Write(output,0, output.Length);

// Method 3 | FileStream | 147 ms !!!! :|
FileStream outfile = new FileStream("outputfile",FileMode.Create,FileAccess.ReadWrite);
file1.CopyTo(outfile);

Also , file1.ToArray() only takes 90 ms to convert ms to bytes.

Why is this happening and what is the reason and logic behind it?

0 answers