Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are returned objects copied?

Say I have the following code:

Frame process(Frame input) {
 if (rareEvent) {
  input = new Frame();
 }
 input.bytes[0] = 255;
 return input;
}

//Elsewhere...
Frame example = new Frame();
example.bytes[0] = 127;
example = process(example);

Obviously, in the rare event that the input Frame object is recreated, it won't be the the exact same object. However, the end goal is that, under normal circumstances (rareEvent registers false), the Frame's bytes property will never be fully copied. This is because, in the actual scenario, it will be millions of bytes long, in a very time-sensitive operation.

In this particular case, I'm not too concerned about whether the rest of the object is truly identical, only its properties. But, for the sake of completion, I may as well inquire to both: If an object passed as a parameter is then returned, is it the exact same (==) object? And in my particular case, will the object's properties avoid any costly copying?

like image 533
DigitalMan Avatar asked May 18 '26 16:05

DigitalMan


1 Answers

Only an object's reference is returned, i.e. it isn't copied. Primitive values (int, double, etc) are copied, however.

like image 196
Zim-Zam O'Pootertoot Avatar answered May 20 '26 06:05

Zim-Zam O'Pootertoot



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!