For certain reasons, I have to create a 1024 kb .txt file.
Below is my current code:
int size = 1024000 //1024 kb..
byte[] bytearray = new byte[size];
foreach (byte bit in bytearray)
{
bit = 0;
}
string tobewritten = string.Empty;
foreach (byte bit in bytearray)
{
tobewritten += bit.ToString();
}
//newPath is local directory, where I store the created file
using (System.IO.StreamWriter sw = File.CreateText(newPath))
{
sw.WriteLine(tobewritten);
}
I have to wait at least 30 minutes to execute this piece of code, which I consider too long.
Now, I would like to ask for advice on how to actually achieve my mentioned objective effectively. Are there any alternatives to do this task? Am I writing bad code? Any help is appreciated.
There are several misunderstandings in the code you provided:
You seem to think that your are initializing each byte in your array
bytearraywith zero. Instead you just set the loop variablebit(unfortunate naming) to zerosizetimes. Actually this code wouldn’t even compile since you cannot assign to the foreach iteration variable.Also you didn’t need initialization here in the first place: byte array elements are automatically initialized to 0.
You want to combine the string representation of each byte in your array to the string variable
tobewritten. Since strings are immutable you create a new string for each element that has to be garbage collected along with the string you created forbit, this is relatively expensive, especially when you create 2048000 one of them – use aStringbuilderinstead.Lastly all of that is not needed at all anyway – it seems you just want to write a bunch of “0” characters to a text file – if you are not worried about creating a single large string of zeros (it depends on the value of
sizewhether this makes sense) you can just create the string directly to do this one go – or alternatively write a smaller string directly to the stream a bunch of times.