考虑
Java中的以下两段代码,
Integer x=new Integer(100);
Integer y=x;
Integer z=x;
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
在我的系统上测试时的内存使用情况:使用的内存(字节):287848
和
int a=100;
int b=a;
int c=a;
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
在我的系统上测试时的内存使用情况:使用的内存(字节):287872
和以下
Integer x=new Integer(100);
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
和
int a=100;
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
在上述两种情况下,在我的系统上测试时内存使用情况完全相同:使用的内存(字节):287872
该声明
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
将显示当前正在使用的总内存[可用内存总量 – 当前可用内存],(以字节为单位).
我已经通过上述方法验证了在第一种情况下,内存使用(287848)低于第二种(287872),而在其余两种情况下,它完全相同(287872).当然,显然,它应该是这样的,因为在第一种情况下,y和z包含x中保存的引用的副本,并且它们的所有(x,y和z)指向相同/共同的对象(位置)意味着第一种情况比第二种情况更好,更合适,在这两种情况的其余情况下,存在具有完全相同的内存使用情况的等效语句(287872).如果是这样的话,那么在Java中使用原始数据类型应该是无用的并且可以避免,尽管它们基本上是为了更好的内存使用和更高的CPU利用率而设计的.为什么Java中的原始数据类型存在?
有点类似于这个问题的问题已在这里发布,但它没有这样的情况.