DigitalMan
DigitalMan

Reputation: 2540

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?

Upvotes: 3

Views: 93

Answers (2)

Fire Static
Fire Static

Reputation: 37

use return this;

Therefore:

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

This would return as an object because of: this

Upvotes: -2

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18148

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

Upvotes: 5

Related Questions