views:

111

answers:

5

Is there a performance cost to static inner class? Or should I just write the same static class as a non-inner class?

+5  A: 

If your business/data logic determines that a class should be an inner class then make it an inner class.

If you are having performance problems take measurements to determine where the problem is and then work out what optimisations to make.

ChrisF
+1 for the millionth time :) write it in the way that works best for you. Only worry about performance when performance is bad.
Rex M
A: 

None. but who cares.

irreputable
+1  A: 

Nesting classes is about semantics and visibility and these are almost always much more important then performance.

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. (Donald Knuth)

Besides that I am quite confident that there is no (important) performance difference - it is just a normal class with different visibility. Maybe there are some subtle difference during class initalization or when using reflection but that should hardly matter.

Daniel Brückner
A: 

According to this test I just ran*, there's no difference.

public static class OuterClass
{
    public static int GetNumber()
    {
        return 1;
    }

    public static string GetString()
    {
        return "Hello, World!";
    }
}

public class Program
{
    private static class InnerClass
    {
        public static int GetNumber()
        {
            return 1;
        }

        public static string GetString()
        {
            return "Hello, World!";
        }
    }

    const int N = 1000000;

    public static void Main()
    {
        var sw = Stopwatch.StartNew();
        for (int i = 0; i < N; ++i)
        {
            int x = OuterClass.GetNumber();
            string s = OuterClass.GetString();
        }
        sw.Stop();

        TimeSpan outerTime = sw.Elapsed;

        sw.Reset();
        sw.Start();
        for (int i = 0; i < N; ++i)
        {
            int x = InnerClass.GetNumber();
            string s = InnerClass.GetString();
        }
        sw.Stop();

        TimeSpan innerTime = sw.Elapsed;

        Console.WriteLine("Outer took {0:0.00} ms.", outerTime.TotalMilliseconds);
        Console.WriteLine("Inner took {0:0.00} ms.", innerTime.TotalMilliseconds);
    }
}

Output:

Outer took 0.28 ms.
Inner took 0.27 ms.

I ran it a few times and the numbers were consistently the same.

*I am assuming you were asking about the cost of accessing members (e.g., invoking method calls) of outer static vs. inner static classes. If I misunderstood, this test is irrelevant.

Dan Tao
A: 

No, but there are some serious semantic issues if you are using nested classes with generics. (Though some of those issues are quite positive, like how an inner class inherits the parent class's type parameters.)

Jonathan Allen