简体   繁体   English

在Java中将大对象作为参数传递是否效率低下?

[英]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? 比方说,我有一个类A,它创建一个相当大的对象B的实例。是否将B作为参数传递给C类中的方法效率低下?

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. 重要的是要理解Java中任何表达式的值永远不是对象。 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: Java只能将两种值传递给方法:

  • primitive values ( int , char , double , ...) or 原始值( intchardouble ,...)或
  • 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". 这意味着你不必担心你的物体“有多大”,你“绕过”。

它效率不高,因为只有对象引用传递给方法。

只要您的调用是本地的(相同的JVM)对象大小无关紧要,但是当您的应用程序使用远程调用(如RMI / Web Service)(跨JVM)时,大型对象能够在很大程度上减慢您的应用程序因为巨大的将被编组/解组的数据量以及每个远程调用所涉及的网络延迟。

As others have said, in Java you only have pass-by-value. 正如其他人所说,在Java中你只有价值传递。 These values are only primitives and references. 这些值只是基元和引用。 The largest a primitive or reference can be is 8-bytes. 最大的基元或引用可以是8字节。 IMHO, there is no such thing as a large argument. 恕我直言,没有大论点这样的事情。

没有什么比内存移位...它只是传递实际的参考..而参考词本身代表一些地址..所以没有问题..它的效率比参数传递真正使代码更复杂..可能就是为什么SUN把它添加到java ...

它只是将引用作为值传递。

Java passes references to objects by value . Java 按值传递对象引用。 It makes no difference performance-wise whether the object reference being passed to C is big or not. 对于传递给C的对象引用是否很大,在性能方面没有区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM