类层次结构对java性能影响有多大?
我有一个类扩展了另一个类,扩展了另一个类......等等。
具有 100 级层次结构级别的类与具有 10 级层次结构级别的类相比,运行速度有多慢(百分比)?
I have class that extends another class, that extend another class.. and so on.
How slow (in percent) class with 100-level hierarchy level will work, then class with 10-level hierarchy level?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
让我们尝试一下:
我能够实例化 T53,但 T54 之后抛出 StackOverflowError。
这是使用默认 JVM 堆栈大小完成的。
对于 100 级层次结构,您将需要更大的堆栈。 (您可以使用
Xss
增加堆栈大小。)Let's try it out:
I was able to instantiate T53, but T54 onwards threw a StackOverflowError.
This was done using the default JVM stack size.
For a 100-level hierarchy you will need a larger stack. (You can increase your stack size using
Xss
.)“好的 JVM”(无论这意味着什么)会缓存方法解析的结果。因此,性能影响应该只发生一次,即使这种影响也可能很小。然而,在对象创建时
每个扩展类的实例也会被创建每个超类的每个构造函数都会被调用,这可能在创建大量对象时会产生更大的影响具有大层次结构的对象。我必须同意乔恩·斯基特(好吧,谁不同意)的观点,因为这个问题听起来像是存在一些严重的设计问题或代码生成器变得异常。这类似于询问“数据库表支持多少列”。如果它超过合理,那么你可能做错了。
"Good JVMs" (whatever that means) cache the results of method resolution. Performance impact therefore should occur only once and even that will likely be minimal. However, on object creation time
an instance of every extended class will be created tooevery constructor of every superclass will be called, which might result in a bigger impact when creating a lot of objects that have large hierarchies.I have to concur with Jon Skeet (well, who doesn't) in that the question sounds like there are some serious design issues or a code generator gone rogue. It's akin to asking "how many columns does a database table support". If it's more than reasonable, you're probably doing it wrong.
这将取决于您的 JVM、您正在执行的确切操作、是否覆盖各种方法等。
然而,我更关心设计和可读性影响,而不是性能影响。这真的是您能想到的最好的设计吗?它解决了什么问题,但不能用其他方式更好地解决?
That will depend on your JVM, the exact operations you're performing, whether various methods are overridden etc.
I would be far more concerned about the design and readability impact than the performance impact, however. Is this really the best design you can come up with? What problem does it solve that couldn't be better solved in a different way?
根据 Java2 Complete Reference 作者 Herbert Schildr 的说法:
我也同意乔恩·斯基特的回答。
As per the Java2 Complete Reference Author Herbert Schildr :
I am also agree with Jon Skeet answer.