I use code like:
Double getabsValue(final Object[] value){
if (value==null) return null;
if (value.lengt==0) return null;
final Double absValue=Maths.abs(value[0]);
if (absValue>0) return absValue
else return null;
But in my application I have problem with performance.
How it can be optimized?
Maybe better use?
if (absValue>0) return absValue
else return absValue<0?-absValue:null;
Thanks
Well, the code you’ve got at the moment won’t even compile – there’s no
Math.abs(Object)call as far as I’m aware. However, assuming you actually have a cast toDoublethere, you’re going to be boxing all the time. You could avoid boxing when the value is already greater than 0, and avoid the call when the value is 0, like this:By the time we get to the final option, we already know that the value is negative, so we don’t really need the call to
absany more.It’s not really clear what the context is here. You say you’ve got a performance problem, but is it definitely in this code?
EDIT: Your latest code shows:
That doesn’t do the same thing – it doesn’t return null if the array contains a boxed 0 value, as your original code does.
You should focus on correctness before performance.
What do you want your code to do with an input of 0? If you want it to return 0, then I would use:
If you want it to return null, use the code I provided originally.
Why include a multiplication by -1 rather than just use the unary negation operator, by the way? I would expect either the compiler or the JIT to get rid of that anyway, but fundamentally you don’t want to be performing multiplication – you want to perform negation. Make your code read as closely as possible to how you’d describe your aims.