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?
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?
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.
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.
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.
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.
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.
© 2022 - 2024 — McMap. All rights reserved.