[英]How does Java allocate memory differently for an object declared in a constructor and an object named by a variable?
Using Java IO streams, it is quite often we use objects solely as constructors for other objects. 使用Java IO流,通常我们仅将对象用作其他对象的构造函数。 I am interested in the memory implications of this prospect. 我对这种前景的记忆含义很感兴趣。 For example, how does memory allocation differ in these two statements that do the same thing? 例如,在执行相同操作的这两个语句中,内存分配有何不同?
FileInputStream inputFile = new FileInputStream("filepath");
Scanner inStream = new Scanner(inputFile);
and 和
Scanner inStream = new Scanner(new FileInputStream("filepath"));
The first one will allocate a named variable in the current stack frame. 第一个将在当前堆栈帧中分配一个命名变量。 On the heap, there is no difference - or there shouldn't be but the VM is of course free to optimize the code in some way as long as the rules are obeyed. 在堆上,没有区别-或应该没有区别,但是VM只要遵循规则,就可以自由地以某种方式优化代码。
没有区别。两者都是一样的。
在第一个示例中,JVM保留对FileInputStream的引用,而在第二个示例中,JVM创建一个未引用的对象,该对象准备在执行该语句后进行垃圾收集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.