This is a mirror of official site: http://jasper-net.blogspot.com/

Struct vs. Class, Safety vs. Speed

| Tuesday, January 17, 2012
While at CodeMash, I had an interesting conversation with Cori Drew regarding some code in Effective C#, and some comments from Jon Skeet in our combined async talks. These comments involve breaking some common recommendations, and performance.

In our talk, Jon described how the C# compiler creates a mutable struct when it builds the state machine that handles async continuations. Jon discussed that the nested struct was faster than a nested class. Contrast that with code in Effective C#, where I showed the following code:

public class List<T> : IEnumerable<T>
{
    private class Enumerator<T> : IEnumerator<T>
    {
        // elided
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new Enumerator<T>();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new Enumerator<T>();
    }
}


Well, Cori asked, why didn’t I make the Enumerator<T> a struct (which is what the BCL does):

public class List<T> : IEnumerable<T>
{
    private struct Enumerator<T> : IEnumerator<T>
    {
        // elided
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new Enumerator<T>();
    }


Read more: Bill Wagner
QR: StructvsClassSafetyvsSpeed

Posted via email from Jasper-net

0 comments: