简体   繁体   English

向Java类添加方法是否会增加其实例的内存使用量?

[英]Does adding methods to a Java class boost the memory usage of its instances?

Adding member variables to a class certainly boosts the memory footprint of its instances on the heap, but what about a class's methods? 将成员变量添加到类中肯定会增加其实例在堆上的内存占用量,但是类的方法呢?

For example, if I have a class composed of a single StringBuilder, but keep adding dozens of methods to manipulate that StringBuilder, will each instance of that class take up proportionally more memory as I add more methods? 例如,如果我有一个由单个StringBuilder组成的类,但是继续添加许多方法来操作StringBuilder,那么当我添加更多方法时,该类的每个实例是否会占用更多的内存?

Thanks! 谢谢!

No, adding methods does not increase the footprint of the object, only the footprint of the compiled code. 不,添加方法不会增加对象的占用空间,只会增加编译代码的占用空间。 In other words, the per-instance memory cost is zero. 换句话说,每实例内存成本为零。

The short answer is no, it will not add more memory to each object living in the heap. 简短的回答是否定的,它不会为生活在堆中的每个对象增加更多内存。 The only thing that will happen is when the class is first loaded, it will also load this methods. 唯一会发生的事情是首次加载类时,它也会加载这些方法。

这是特定于VM的,但对于每个人使用的Oracle Hotspot VM,不,实例大小不受影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM