I am facing a performance issue when using the FileStream.Write function.
I have a console application that I use to read a Base64 string from a file (400 KB in size) using a StreamReader object. I convert this string to an array of bytes using Convert.FromBase64String. Then I write this byte array to a file using a FileStream object. The resulting byte array length was 334991.
I measured the time taken to write an array of bytes, and it takes about 0.116 seconds.
Just for fun, I got an array of bytes from the same Base64 encoded string using the ASCIIEncoding.GetBytes function (although I knew that this would not give the correct DECODED result - I just wanted to try). I wrote this byte array to a file using a FileStream object. The resulting byte array length was 458414.
I measured the time taken to write an array of bytes using this methodology, and it is approximately 0.008 seconds.
Here is a sample code:
class Program { static void Main(string[] args) { Stopwatch stopWatch = new Stopwatch(); TimeSpan executionTime; StreamReader sr = new StreamReader("foo.txt"); string sampleString = sr.ReadToEnd(); sr.Close();
I ran tests for about 5,000 files containing Base64 encoding, and the difference between the time it takes to write these two types of byte array is almost 10 times (with the one that writes the byte array using real , taking more time).
The length of the byte array obtained using Convert.FromBase64String is less than the length obtained using the ASCIIEncoding.GetBytes function.
Interestingly, all I'm trying to do is write a bunch of bytes using a FileStream object. So, why should there be such a sharp difference in performance (wrt time) when writing an array of bytes to disk?
Or am I doing something terribly wrong? Please advise.
source share