Reputation: 24248
I have expression:
Double getAbs(Double value){
return value> 0 ? value: value== 0 ? null : -value;
}
or better:
Double getAbs(Double value){
return Math.abs(value);
}
I understand that there are some differences about NaN. But method Math.abs(double) - so we have unboxing. In which case performance better?
Upvotes: 3
Views: 9389
Reputation: 1392
I just had a look at SunOracle's implementation and this is how they've implemented it
public static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a;
}
Except for the cost of unboxing and autoboxing params and return values, there shouldn't be any other performance impact.
Upvotes: 4
Reputation: 89169
The only "performance" in your code is that the JVM will need to unbox your Double
to double
.
Math.abs(double)
uses a ternary if statement as follows:
public static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a;
}
So, your if
statement is no performance worry at all.
Upvotes: 8
Reputation: 56479
No usually, Math.abs()
is not slower than yours. Because JVM can implement its math operation according to the target machine. and It can be faster than your implementation.
Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math.
For more information read this.
Anyway, if you need better performance -in this case- you can use double
instead of Double
and forget your getAbs()
and use Math.abs()
directly.
Upvotes: 4