有多个内部类会使对象初始化变慢吗? [英] Does having multiple inner classes makes object initialization slow?

查看:64
本文介绍了有多个内部类会使对象初始化变慢吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class OuterClass
{
    public class Inner1
    {}

     public class Inner2
    {}
}

推荐答案

没有。这根本没关系。为什么?



尽管我看到一些针对嵌套类型的强烈反对意见,但它们只是关于可读性,维护,但大多数重要的是,我认为所有这些警告只是骗局。 嵌套类型绝对没有问题,如果合理使用它们。这只是一种额外的封装方式。



另外,你应该理解,内部类型与类型的初始化无关,构造一个类型实例。比如说,如果你创建一个 OuterClass 的实例,那么仅仅存在两个内部类将根本不会影响它,除非它们也被实例化为<$ c的一部分$ c> OuterClass ,可能会也可能不会发生。但是当它发生时,声明这些类型的位置并不重要。



一般来说,如果你对性能有任何疑虑,你可以轻松地试验它。有时它非常有用(在其他一些情况下,我的意思是)。您总是可以编写两个完全相同的代码片段并为其计时。您可以使用类 System.Diagnostics.Stopwatch 进行非常精确的计时:

http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch%28v=vs。 110%29.aspx [ ^ ]。



在计时时,你应该避免一个警告;你需要排除JIT编译的时间,这通常是在运行时执行的,通常是在每个方法的基础上,当第一次调用某个方法时。为避免此问题,您不应该从计时中包含每个方法的第一次调用。请参阅:

http://en.wikipedia.org/wiki/Just-in -time_compilation [ ^ ]。< br $>


-SA
No. It does not matter at all. Why?

Even though I saw some strong objections against nested types, they were only about readability, maintenance, but most importantly, I think all those warning are just scam. There is absolutely nothing wrong with nested types, if they are used reasonably. This is just one extra way of encapsulation.

Also, you should understand that having the inner type has nothing to do with initialization of the type, constructing a type instance. Say, if you create an instance of OuterClass, mere presence of two inner classes won't effect it at all, unless the are also instantiated as the part of the OuterClass, which may or may not happen. But when it happens, it does not matter where those types are declared.

Generally, if you have any concerns about performance, you can easily experiment with it. Sometimes it is very useful (in some other cases, I mean). You can always write two fully equivalent pieces of code and time it. You can do very precise timing using the class System.Diagnostics.Stopwatch:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch%28v=vs.110%29.aspx[^].

When timing, you should avoid one caveat; you need to exclude the time for JIT compilation, which actually is performed during runtime, normally, on per-method basis, when some method is called for the very first time. To avoid the problem, you should never include very first calls of each method from timing. Please see:
http://en.wikipedia.org/wiki/Just-in-time_compilation[^].

—SA


这篇关于有多个内部类会使对象初始化变慢吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆