java - 由于性能问题双重字符串替代

标签 java performance

需要帮助寻找替代品。这是我在环境中运行的当前代码。看起来它影响了我的应用程序的性能并且速度不够快。我正在考虑 try-catch 方法。它会工作还是有更好的选择可以建议将 double 转换为字符串?

public static String formatDoubleValue(String string) {

    if (string == null)
        return null;

    if (string.matches("-?\\d+(\\.\\d+)")) {
        //System.out.println(string + " is a Double");
        Double dVal = Double.parseDouble(string);
        //System.out.println("Formatted value: " + NUM_FORMAT.format(dVal));
        return NUM_FORMAT.format(dVal);
    } else {
        //System.out.println(string + " is not a Double");
        return string;
    }
}

public static String formatDoubleValuesixdigit(String string) {

    if (string == null)
        return null;

    if (string.matches("-?\\d+(\\.\\d+)")) {
        //System.out.println(string + " is a Double");
        Double dVal = Double.parseDouble(string);
        //System.out.println("Formatted value: " + NUM_FORMAT.format(dVal));
        return NUM_FORMAT_SIXDIGIT.format(dVal);
    } else {
        //System.out.println(string + " is not a Double");
        return string;
    }
}

最佳答案

很难提出替代方案,因为我们不确切知道您希望如何格式化数字。

但是,每次执行此行时:

if (string.matches("-?\\d+(\\.\\d+)")) {

您正在重新编译一个正则表达式。这将相当缓慢。

编译一次,存入字段:

static final Pattern PATTERN = Pattern.compile("-?\\d+(\\.\\d+)");

然后在条件中使用它:

if (PATTERN.matcher(string).matches()) {

关于java - 由于性能问题双重字符串替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58772425/

相关文章:

java - 无法从 linux 中的 eclipse juno 端口 80 启动 Apache tomcat

java - org.mockito.exceptions.misusing.InvalidUseOfMatchersException' 异常

php - 消息系统,存储在数据库中还是文件系统中更好?

reactjs - React 中的延迟加载和列表虚拟化有什么区别?

具有(非常)快速和可靠切换的 C++ 生产者消费者队列

java - 如何根据从数据库中获取的数据一般地构造对象

java 用正则表达式分割字符串

java - Java如何区分这些具有相同名称/签名的多个方法?

c++ - 原生类型的封装会影响效率吗?

java - 链表 getValue(int n) 应该是 O(n/2)