简体   繁体   中英

Passing big objects references instead of small objects to methods have any differences in processing or memory consumption?

I have a coding dilemma, and I don't know if there's a pattern or practice that deals with it. Whenever I have to pass some values to a method, most times I try to pass only the needed objects, instead of passing the objects which are being composed by them. I was discussing with a friend about how Java manages heap and memory stuff and we didn't get anywhere.

Let me give two examples:

//Example 1:
private void method doSomething(String s, Car car, boolean isReal){...}
...
String s        = myBigObject.getLabels.getMainName();
Car car         = myBigObject.getCar();
boolean isReal  = myBigObject.isRealCar();

doSomething(s, car, isReal);

//Example 2 - having in mind that BigObject is a really big object and I'll only use those 3 atributes:
private void method doSomething(BigObject bigObject){...}
...

doSomething(myBigObject);

In the 2nd example, it seems to me memory will be kind of wasted, passing a big object without really needing it.

Since Java passes only references to objects (and copies them, making it technically pass-by-value), there is no memory overhead for passing "big objects". Your Example 1 actually uses a little more memory.

However, there may still be good reason to do it that way: it removes a dependency and allows you to call doSomething on data that is not part of a BigObject . This may or may not be an advantage. If it gets called a lot with BigObject parameters, you'd have a lot of duplicate code extracting those values, which would not be good.

Note also that you don't have to assign return values to a local variable to pass them. You can also do it like this:

doSomething(myBigObject.getLabels().getMainName(), 
            myBigObject.getCar(), 
            myBigObject.isRealCar());

You're already only passing a reference to BigObject , not a full copy of BigObject . Java passes references by value.

Arguably, you're spending more memory the first way, not less, since you're now passing two references and a boolean instead of a single reference.

Java uses pass by value, when ever we pass an object to a method keep in mind that we are not going to pass all the values store in side the object we just pass the bits( some thing like this ab06789c) which is the value of the address on which the object is stored in memory( Heap Memory ). So you are wasting more memory in first case rather than the 2nd one.
Refer to JAVA pass-by-reference or pass-by-memory

All references are the same size, so how could it use more memory? It doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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