Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using StreamWriter constructor and File.CreateText

What's the difference (CPU usage, MSIL, etc) between:

StreamWriter sw = new StreamWriter("C:\test.txt");

and:

StreamWriter sw = File.CreateText("C:\test.txt");

?

like image 257
Keyo Avatar asked Jul 21 '10 23:07

Keyo


1 Answers

Not much... (via Reflector)

[SecuritySafeCritical]
public static StreamWriter CreateText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    return new StreamWriter(path, false);  // append=false is the default anyway
}

For what it's worth though I prefer using File.* factory methods because I think they look cleaner and are more readable than passing a bunch of constructor parameters to Stream or StreamWriter because it's hard to remember which overloads do what if you're not looking at the definition.

Also, JIT compilation will almost certainly inline the call anyway so even the miniscule overhead of a single additional method call will likely not be incurred.

like image 130
Josh Avatar answered Nov 14 '22 22:11

Josh