Well if I were working in a carnival and this thing stepped up to the booth to have me guess its weight, it would have won the coveted stuffed animal for its dollar.
This is really obvious though it might be more of an optimization than your think, caught me by surprise anyways I was expecting a 7.5-15% gain from it which is why I had put it off as a "minor" optimization to do when I had a few free minutes.
If you have a guess at the size of the file you would like to write, size it before hand truncate after if need be ... its pretty much free.
namespace BigFileWriterTest
{
class Program
{
static FileStream CreateAndOpenFile(string _Name)
{
FileStream ret = File.Open(_Name, FileMode.Create);
return ret;
}
static void TestFile(string _Name, bool _InitSize, int Megs) {
Stopwatch sw = new Stopwatch();
byte[] data = new byte[1024]; //1 kb buffer
for (int i = 0; i < data.Length; i++)
{
data
= (byte) (i % 255);
}
sw.Start();
using (FileStream fs = CreateAndOpenFile(_Name))
{
sw.Stop();
Console.WriteLine("Open: " + sw.Elapsed);
sw.Reset();
sw.Start();
if (_InitSize)
{
long length = 1024;
length = length * 1024;
length = length * Megs;
fs.SetLength(length);
}
sw.Stop();
Console.WriteLine ("Length Increase: " + sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < (Megs * 1024); i++)
{
fs.Write (data, 0, data.Length);
fs.Flush();
}
sw.Stop();
Console.WriteLine("Write: " + sw.Elapsed);
fs.Close();
}
File.Delete(_Name);
}
static void Main(string[] args)
{
string Filename = "C:\\shitbird.tmp";
TestFile(Filename, false, 1000);
TestFile(Filename, true, 1000);
}
}
Output:
Open: 00:00:00.0013021
Length Increase: 00:00:00.0000013
Write: 00:01:17.4923097
Open: 00:00:00.0013376
Length Increase: 00:00:00.0220189
Write: 00:00:13.8646638
Press any key to continue . . .
WOW!
77
---- = almost 6 times faster?!
13
Go try it on yours and show your boss how you made that big dump file 5x faster, it should at least get you a beer.
p.s. no comments on my temp file names :) they are really easy to find/delete.