Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 446
Marcelo Assis Avatar asked Dec 03 '25 10:12

Marcelo Assis


2 Answers

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());
like image 134
Michael Borgwardt Avatar answered Dec 05 '25 00:12

Michael Borgwardt


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.

like image 36
Louis Wasserman Avatar answered Dec 05 '25 00:12

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!