this code times 2 methods of outputting ~380kb string:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.diagnostics; namespace consoleapplication1 { class program { static string outbuff = ""; static void main(string[] args) { { stopwatch exectime = new stopwatch(); system.io.streamwriter file; exectime.reset(); exectime.start(); file = new system.io.streamwriter("output.html"); (int = 0; < 18000; i++) { outbuff += "444444444, 5555555555\n"; } string fin = "\nstring method took " + exectime.elapsed.totalseconds + "s"; file.writeline(outbuff); console.writeline(fin); file.writeline(fin); file.close(); } { stopwatch exectime = new stopwatch(); system.io.streamwriter file; exectime.reset(); exectime.start(); file = new system.io.streamwriter("output2.html"); (int = 0; < 18000; i++) { file.write("444444444, 5555555555\n"); } string fin = "\ndirect method took " + exectime.elapsed.totalseconds + "s"; console.writeline(fin); file.writeline(fin); file.close(); } } } }
string method took 2.2985349s direct method took 0.07191s
this on 3.5ghz cpu 5gb ram.
i'm disappointed buffering output in string costly!
in real program, need deferr output until string assembled. there faster way?
yes, use stringbuilder
instead assemble string.
for in-depth explanation performance boost see "using stringbuilder class" - because strings immutable new string created when concatenate, expensive.
Comments
Post a Comment