Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果我们不';t分配方法返回的值是否仍会增加内存使用率?_Java_Memory - Fatal编程技术网

Java 如果我们不';t分配方法返回的值是否仍会增加内存使用率?

Java 如果我们不';t分配方法返回的值是否仍会增加内存使用率?,java,memory,Java,Memory,比如说, if方法返回大量数据,如: Data[] data = getData(); //will return 100Mb. Java memory usage increased by 100 如果我们调用getData而不对数据进行赋值,java会使用100Mb吗 getData(); //returns huge data but we don't assign it to var. Memory usage wasn't increased 赋值本身不使用任何内存,创建这些对象时

比如说,

if方法返回大量数据,如:

Data[] data = getData(); //will return 100Mb. Java memory usage increased by 100
如果我们调用getData而不对数据进行赋值,java会使用100Mb吗

getData(); //returns huge data but we don't assign it to var. Memory usage wasn't increased

赋值本身不使用任何内存,创建这些对象时使用内存。因此,如果您的方法创建了一个100MB的对象,那么这个内存需求将不会减少。但是如果您不分配它,它将很快被垃圾收集(除非它保留在其他地方)。

是的<代码>数据[]数据只是对数据的引用。因此,它将使用100MB


但是,如果您没有将返回的数据分配给任何变量,并且它没有任何其他引用,则数据将很快被垃圾收集并释放内存。

是的,即使我们没有将数据分配给任何变量,数据也会被调用。变量仅用于引用该值

例如:

使用变量

Object a = getData();
otherFunction1(a);  //calling any other using variable reference
otherFunction1(getData());  //calling any other using variable reference
不使用变量

Object a = getData();
otherFunction1(a);  //calling any other using variable reference
otherFunction1(getData());  //calling any other using variable reference
区别在于我们没有引用getData()的值。因此,如果我们有任何其他函数,比如otherFunction2,我们可以将值传递为:

例1:

otherFunction2(a)
例2

otherFunction2(getData()) //need to recall the function getData()

谢谢

丢弃对象不会增加内存使用,只会减少内存使用。这是因为GC之后使用的内存是被引用对象的内存。引用的对象越少,使用的内存就越少


顺便说一句,100 MB的PC内存成本约为0.30美元,并且可重复使用,因此不会太大。

是的,但很快就会被垃圾回收。如果没有收到内存溢出。
b
=>
b
=>字节。e、 g.如果您有
1 Gb/s
网卡,它是每秒1千兆位,而不是字节。我假设您的意思是
100MB
请注意,JVM可能会删除任何不必要的分配和/或方法调用,只要它们没有副作用,作为运行时字节码优化的一部分。但是您不应该依赖于此。如果适用,您可以实现一个自定义列表,在get()中动态创建项目。这样,您就不必将它们全部存储在内存中。不幸的是,这在大多数情况下并不适用。