继承中的Java内存使用情况 [英] Java memory usage in inheritance

查看:92
本文介绍了继承中的Java内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展基类时,Java中的内存使用情况如何。

What does the memory usage look like in Java when extending a base class.

子类是否包含基类的实例(具有自己的开销和所有)或它只有16字节的开销吗?

Do the child class contain an instance of the base class (with it's own overhead and all) or does it only have it's own overhead of 16 Bytes?

class Foo {
 int x;
}

class Bar extends Foo {
 int y;
}

因此,更具体地说,Bar实例的内存使用量是多少?

So, more specifically, what is the memory usage of an instance of Bar?

是否 Foo(包括间接费用)+ Bar(包括间接费用)

或只是 Foo(不包括间接费用+ Bar(包括间接费用)

推荐答案

没有双重开销。

Java将使用类,超类,计算所有字段所需的空间,并分配所需的空间单个实例。

Java will take the class, the superclasses, compute the space needed for all the fields, and allocate space needed for one single instance.

仅形成一个内存观点,根本不存在超类的概念,有一个Foo实例只需要一个int的内存和Bar的实例需要两个整数的内存,其中一个是因为Bar恰好扩展了Foo。

Form a memory point of view only, there does not exist the notion of superclass at all, there are instance of Foo that need memory for only one int, and instances of Bar that need memory for two ints, of which one is there because Bar happens to extend Foo.

所以开销(或记账或任何你想要的调用)只发生一次。

So the overhead (or bookkeeping or whatever you want to call) happens only once.

但是,在java中开发时,通常最好不要关心内存tuff太多了,除非你有非常具体的(我的意思是非常非常具体的)用例,其中bookkingping开销导致你严重的问题。在这种情况下,还应考虑8字节填充。

However, when developing in java, is usually better not to care about memory stuff too much, unless you have very specific (and i mean very very very specific) use cases on which the bookkeping overhead is causing you serious problems. In that case, also the 8 byte padding should be considered.

通常,还有许多其他方法可以改善应用程序的内存占用或整体性能,不要担心每个实例的内存开销。

Usually, there are many other ways you can improve the memory footprint of your application or it's overall performance, than not worrying about the memory overhead of each single instance.

这篇关于继承中的Java内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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