rtheunissen
rtheunissen

Reputation: 7435

Is it inefficient to pass large objects as parameters in Java?

Let's say for example I have a class A that creates an instance of a fairly big object B. Is passing B as a parameter to a method in a class C inefficient?

That is, does it just pass a reference or does it shift the object's memory around as well?

Thanks.

Upvotes: 42

Views: 15346

Answers (8)

sanjaygarde
sanjaygarde

Reputation: 377

As long as your calls are local (same JVM) object size should not matter, however when your application uses remote calls like RMI / Web Service (across JVMs) the large objects are capable of slowing down your application to a great extent because of huge amount of data that will be marshalled / unmarshalled and the network latency involved for every remote call.

Upvotes: 5

otto
otto

Reputation: 1158

Java passes references to objects by value. It makes no difference performance-wise whether the object reference being passed to C is big or not.

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308001

Java can only pass two kinds of values to a method:

  • primitive values (int, char, double, ...) or
  • object references

There is no way you can pass a whole object "by value".

This means that you don't need to worry about "how big" your object is that you "pass around".

Upvotes: 21

Peter Lawrey
Peter Lawrey

Reputation: 533492

As others have said, in Java you only have pass-by-value. These values are only primitives and references. The largest a primitive or reference can be is 8-bytes. IMHO, there is no such thing as a large argument.

Upvotes: 3

ngesh
ngesh

Reputation: 13501

There is nothing like memory Shifting.. it just passes the actual reference.. and the reference word itself stands for some address.. so no issue.. its efficient than parameter passing which really makes code more complex.. may be thats why SUN added it to java...

Upvotes: 2

Prince John Wesley
Prince John Wesley

Reputation: 63688

It just pass a reference as value.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500055

It just passes a reference. It's important to understand that the value of any expression in Java is never an object. It's only ever a reference or a primitive value.

This isn't just relevant for parameter passing - it's important to understand for return types, arrays, simple assignment etc.

Upvotes: 80

vanje
vanje

Reputation: 10373

It's not inefficient, because only the object reference is passed to the method.

Upvotes: 7

Related Questions