java - Does creating multiple "throwaway" objects affect performance -
example:
is this
public double rounddecimal(double val) { return double.parsedouble(new decimalformat("#,##0.0").format(val)); } double d1 = rounddecimal(val); double d1 = rounddecimal(val); double d1 = rounddecimal(val); // lot more of these...
considered bad practice instead of this?
public double rounddecimal(double val, decimalformat dformat) { return double.parsedouble(dformat.format(val)); } decimalformat dformat = new decimalformat("#,##0.0"); double d1 = rounddecimal(val, dformat); double d1 = rounddecimal(val, dformat); double d1 = rounddecimal(val, dformat); // lot more of these...
the difference of course being instead of creating decimalformat object on , over, create once , resuse it. thoughts garbage collector ensure wouldn't matter, don't understand enough know sure.
you looking @ wrong end. “optimized” variant
public double rounddecimal(double val, decimalformat dformat) { return double.parsedouble(dformat.format(val)); }
creates multiple objects on each call. on api side, format
returns new string
instance pass parsedouble
. below surface both operations, format
, parsedouble
create temporary objects doing work. implementor(s) had no reason worry them, tasks of formatting double
decimal representation , parsing decimal representation double
expensive, outweigh anything.
it’s easy overlook, humans, decimal representations seem natural thing, computer, converting decimal representation , expensive.
but before continue worrying performance, should start worrying correctness. generally, it’s bad idea apply concept formatting double
values. since internal representation fundamentally different decimal numbers, can’t represent tenths exactly. if want controllable precision of kind, bigdecimal
right tool job (yes, objects…). or use result string of formatter
printing or other ui presentation.
besides that, using format string "#,##0.0"
, requesting string grouping separator double.parsedouble
not expect. further, applying decimal format of current user’s locale, if not using .
decimal separator, operation will, break when value small grouping. english locales, passing value 1234
sufficient break method, for, e.g. german locales, break every value.
a work-around use same format parsing used formatting:
public double rounddecimal(double val, decimalformat dformat) { try { return dformat.parse(dformat.format(val)).doublevalue(); } catch (parseexception ex) { throw new assertionerror(ex); } }
but still have desastrous performance, not because of temporary objects created.
after all, if still want use double
values rather bigdecimal
, solution straight-forward:
public double rounddecimal(double val) { return math.round(val*10)/10.0; }
Comments
Post a Comment