How to efficiently write a large text file in C#? -
I am making a method in C # which generates a text file for one. The feed will contain 30,000 records and currently weighs up to ~ 7 MB of text file.
Here is the code that I am currently using (some lines have been deleted for short).
public static zero generateTextFile (string file path) {var sb = new string builder (1000); Sb.Append ("availability") attached ("\ t"). Sb.Append ("condition") attached ("\ t"). Sb.Append ("Description") Engage ("\ t"). For summarized // iterative code is hidden ... sb.Append (EnvironmentalNewLine); Var Items = Inventory Repos GetItemsForSale (); Foreign objects (different P items) {sb.Append ("In Stock"). Attached ("\ t"); . Sb.Append ("old") attached ("\ t"); Sb.Append (p.Description) .Append ("\ t"); For summarized // iterative code is hidden ... sb.AppendLine (); } {Result.Append ("write text file on disk") using the StreamWriter outfile = new StreamWriter (filePath). Appendable (); Outfile.Write (sb.ToString ()); }}
I'm surprised that stringbillers are the right tools for the job, will I have performance advantages using TextWriter instead?
I do not know a ton about IO performance so any help or general improvement will be appreciated. Thank you.
File I / O operations are generally compatible with modern operating systems. You should not try to collect the whole string for the memory in memory ... just piece it in pieces. Flamestream
will take care of buffering and other performance considerations.
You can easily move this change:
using (StreamWriter outfile = new streamer (file path) at the top of the function { < Instead of getting rid of / pre> , and StringBuilder
, the file is writing directly.
There are several reasons to avoid making large stars in memory:
- This can actually perform poorly because
StringBuilder
to increase its capability as you write it, which results in a copy of the reallocation and memory. - You may need more memory than allocated physically - which is a virtual memory (swap file) that is much slower than RAM.
- In fact, for large files (> 2 GB), you will participate in address space (on 32-bit platform) and will fail completely.
- To write a
stringbinder
content, you have to use the ToString ()
which effectively doubles the memory consumption of the process As both copies should be in memory for a period of time. This address may also fail if your address space is broken enough, such that an inner section of memory can not be allocated.
Comments
Post a Comment