Should autoboxing be avoided in Java?

假装没事ソ 提交于 2019-12-19 13:06:06

问题


There are instances where a method expects a primitive type double and you pass a Double object as a parameter.

Since the compiler unboxes the passed object will this increase memory usage or decrease performance?


回答1:


This is what Java Notes says on autoboxing:

Prefer primitive types

Use the primitive types where there is no need for objects for two reasons.

  1. Primitive types may be a lot faster than the corresponding wrapper types, and are never slower.
  2. The immutability (can't be changed after creation) of the wrapper types may make their use impossible.
  3. There can be some unexpected behavior involving == (compare references) and .equals() (compare values). See the reference below for examples.



回答2:


The rule of thumb is: always use primitives if possible.

There are cases where this is not possible, like collections, so use wrappers only then.




回答3:


It's a design-choice and not trivially answered for every case.

There are several items that could influence your decision:

Advantages:

  • Auto-boxing and auto-unboxing can make your code easier to read:

    Leaving out all the unnecessary .doubleValue() and Double.valueOf() reduces the visual noise and can make your code easier to read.

  • Auto-boxing allows you to easily use collections of primitive values (such as a List<Double>, ...)

Disadvantages:

  • excessive, unnecessary auto-boxing and auto-unboxing can hinder your performance.

    For example, if you have an API that returns a double and another API that expects a double, but you handle the value as a Double in between, then you're doing useless auto-boxing.

  • auto-unboxing can introduce a NullPointerException where you don't expect it:

    public void frobnicate(Double d) {
      double result = d / 2;
      // ...
    }
    
  • using collections of auto-boxed values uses a lot more memory than a comparable double[] for example.




回答4:


You don't have to avoid autoboxing if talking about performance, JVM should handle that. The only thing you should consider is a readability of your code.




回答5:


Autoboxing should be avoided. It can lead to errors because of overloading and it has some performance impact. Nonetheless it may not be an issue in your application. But be aware of the impact.

Here my post to that: https://effective-java.com/2010/05/the-advantages-and-traps-of-autoboxing/



来源:https://stackoverflow.com/questions/7610664/should-autoboxing-be-avoided-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!