开发者

Is there a performance cost to static inner class?

开发者 https://www.devze.com 2023-01-08 04:11 出处:网络
Is there a performa开发者_Python百科nce cost to static inner class?Or should I just write the same static class as a non-inner class?If your business/data logic determines that a class should be an in

Is there a performa开发者_Python百科nce cost to static inner class? Or should I just write the same static class as a non-inner class?


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.


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.


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.


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消