我需要以给定的精度将双精度转换为字符串。String.format("%.3f", value)(或 DecimalFormat)可以完成这项工作,但基准测试表明,即使与不是很快的Double.toString转换(在我的机器上转换 100 万个数字大约需要 1-3 秒)相比,它也很慢。
有没有更好的方法来做到这一点?
更新:基准测试结果
从 0 到 1000000 的随机数,结果以每毫秒的操作数为单位(Java 1.7.0_45)
Benchmark                                    Mean   Mean error    Units
String_format                             747.394       13.197   ops/ms
BigDecimal_toPlainString                 1349.552       31.144   ops/ms
DecimalFormat_format                     1890.917       28.886   ops/ms
Double_toString                          3341.941       85.453   ops/ms
DoubleFormatUtil_formatDouble            7760.968       87.630   ops/ms
SO_User_format                          14269.388      168.206   ops/ms
更新:
Java 10,+流
                                Mode  Cnt      Score      Error   Units
String_format                  thrpt   20    998.741 ±   52.704  ops/ms
BigDecimal_toPlainString       thrpt   20   2079.965 ±  101.398  ops/ms
DecimalFormat_format           thrpt   20   2040.792 ±   48.378  ops/ms
Double_toString                thrpt   20   3575.301 ±  112.548  ops/ms
DoubleFormatUtil_formatDouble  thrpt   20   7206.281 ±  307.348  ops/ms
ruy_doubleToString             thrpt   20   9626.312 ±  285.778  ops/ms
SO_User_format                 thrpt   20  17143.901 ± 1307.685  ops/ms