Is performance of "Math.abs()" better than expression with "if"?
I have expression:
Double getAbs(Double value){
return value> 0 ? value: value== 0 ? null : -value;
}
or better:
Double getAbs(Double value){
return Math.ab开发者_如何转开发s(value);
}
I understand that there are some differences about NaN. But method Math.abs(double) - so we have unboxing. In which case performance better?
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.
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.
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.
精彩评论