C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: We call WriteByte on the BufferedStream, which acts upon the MemoryStream. But it buffers operations.
Result: The total time required for the 5 million buffered WriteByte calls is printed as the program exits.
C# program that benchmarks BufferedStream
using System;
using System.Diagnostics;
using System.IO;
class Program
{
static void Main()
{
var t1 = Stopwatch.StartNew();
// Use BufferedStream to buffer writes to a MemoryStream.
using (MemoryStream memory = new MemoryStream())
using (BufferedStream stream = new BufferedStream(memory))
{
// Write a byte 5 million times.
for (int i = 0; i < 5000000; i++)
{
stream.WriteByte(5);
}
}
t1.Stop();
Console.WriteLine("BUFFEREDSTREAM TIME: " + t1.Elapsed.TotalMilliseconds);
}
}
Output
BUFFEREDSTREAM TIME: 20.6607
Result: The 5 million WriteByte calls in this program take an entire 5 milliseconds more than in the version that uses BufferedStream.
C# program that benchmarks MemoryStream, no buffer
using System;
using System.Diagnostics;
using System.IO;
class Program
{
static void Main()
{
var t1 = Stopwatch.StartNew();
// Use MemoryStream directly with no buffering.
using (MemoryStream memory = new MemoryStream())
{
// Write a byte 5 million times.
for (int i = 0; i < 5000000; i++)
{
memory.WriteByte(5);
}
}
t1.Stop();
Console.WriteLine("MEMORYSTREAM TIME: " + t1.Elapsed.TotalMilliseconds);
}
}
Output
MEMORYSTREAM TIME: 26.2119
Tip: Optimal performance is "undecidable" which means no program is optimal because another might someday exist that is faster.