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.
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.
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".
It's not inefficient, because only the object reference is passed to the method.
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.
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.
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...
It just pass a reference as value.
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.
精彩评论