问题
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.
- Primitive types may be a lot faster than the corresponding wrapper types, and are never slower.
- The immutability (can't be changed after creation) of the wrapper types may make their use impossible.
- 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()
andDouble.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 adouble
, 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