FW: [Mono-list] Buffering for StreamWriter

Marsh, Drew dmarsh@mimeo.com
Thu, 16 May 2002 16:16:06 -0400


Dan Lewis [mailto:dihlewis@yahoo.co.uk] wrote:

> In an interview, Anders Hejlsberg said that the using
> construct wasn't in his initial design for C#. He said he 
> added it after the Microsoft developers writing the class 
> libraries asked for a more structured way to control an 
> object's lifetime (maybe they were C++ developers that missed 
> their trusty RAII
> idiom)

Yup... the "using" resource management construct didn't actually make it
into the language until after Beta1 I believe. There was all sorts of
debating over the keyword because "using" already meant something in the
language (i.e. declaring what namespaces you're using), but the word made
such sense in terms of resource management too, so it stuck.

> As you say, you could do without it by using a
> try-catch-finally construct. The using construct gives the C# 
> compiler and developer clearer semantics for a common 
> programming idiom 

Exactly.

> - much like foreach does for the for loop.

Actually, foreach does something different than a for loop would. It calls
IEnumerable::GetEnumerator() and uses the semantics of the IEnumerator
interface to iterate the items in the container. Whereas for would index
into the container each time. Depending on the container, one might be
faster than the other. For example, there's actually an optimization in the
MS JIT right now for arrays, where if you for over an array like so:

<codeSnippet language="C#">
int[] myArray = new int[] { 1, 2, 3 };

for(int index = 0; index < myArray.Length; index++)
{
	Console.WriteLine(myArray[index]);
}
</codeSnippet>

The JIT will do away with bounds checking which will obviously result in a
signifigant performance increase. Gunnerson claims 5x faster than foreach in
his example[1]. It's all about the explicit use of .Length in the
conditional of the for statement.

In the future it's been said that the C# compiler itself will detect a
foreach on an array and instead emit a for loop in IL so that users don't
need to know about this little JIT optimization trick.

Later,
Drew
.NET MVP

[1] Under the subheading "Use For Loops for String Iteration-version 1":
http://www.msdnaa.net/interchange/preview.asp?PeerID=862#perform