views:

73

answers:

1

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

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

and:

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

?

+4  A: 

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.

Josh Einstein
Microsoft is brilliant
Dinoo
"I think they look cleaner" - Yeah, weren't they introduced because people found the Stream*** classes unintuitive? I vaguely recall something in one of Abrams' Framework books about how he thought the Stream** stuff was such a great design and being shocked when he watched devs trying to work with it and not being able to figure it out easily.
kekekela
I am pretty sure they've been there since the beginning. The Stream class itself is a pretty elegant design if you ask me. It is a very good example of the flexibility of the decorator pattern. I just don't like using the constructors explicitly.
Josh Einstein