isNumber(string)方法的最佳实现

tho*_*ncp 18 c# performance

在我有限的经验中,我参与了几个项目,这些项目有一些字符串实用程序类,其中包含确定给定字符串是否为数字的方法.这个想法一直都是一样的,然而,实施却有所不同.有些使用try/catch包围解析尝试

public boolean isInteger(String str) {
    try {
        Integer.parseInt(str);
        return true;
    } catch (NumberFormatException nfe) {}
    return false;
}
Run Code Online (Sandbox Code Playgroud)

和其他人匹配正则表达式

public boolean isInteger(String str) {
    return str.matches("^-?[0-9]+(\\.[0-9]+)?$");
}
Run Code Online (Sandbox Code Playgroud)

这些方法中的一种比另一种更好吗?我个人更喜欢使用正则表达式方法,因为它很简洁,但是如果在迭代过程中调用,例如,数十万个字符串的列表,它会在par上执行吗?

注意:由于我是网站的新手,我不完全理解这个社区Wiki业务,所以如果这属于那里让我知道,我很乐意移动它.

编辑: 有了所有的TryParse建议,我把Asaph的基准代码(感谢一个很棒的帖子!)移植到C#并添加了一个TryParse方法.而且看起来,TryParse赢得了胜利.然而,尝试捕获方法耗费了大量时间.我认为我做错了什么!我还更新了正则表达式来处理负数和小数点.

更新的C#基准代码的结果:

00:00:51.7390000 for isIntegerParseInt
00:00:03.9110000 for isIntegerRegex
00:00:00.3500000 for isIntegerTryParse
Run Code Online (Sandbox Code Playgroud)

使用:

static bool isIntegerParseInt(string str) {
    try {
        int.Parse(str);
        return true;
    } catch (FormatException e){}
    return false;
}

static bool isIntegerRegex(string str) {
    return Regex.Match(str, "^-?[0-9]+(\\.[0-9]+)?$").Success;
}

static bool isIntegerTryParse(string str) {
    int bob;
    return Int32.TryParse(str, out bob);
}
Run Code Online (Sandbox Code Playgroud)

Asa*_*aph 13

我刚刚对这两种方法的性能进行了一些基准测试(在Macbook Pro OSX Leopard Java 6上).ParseInt更快.这是输出:

This operation took 1562 ms.
This operation took 2251 ms.
Run Code Online (Sandbox Code Playgroud)

这是我的基准代码:


public class IsIntegerPerformanceTest {

    public static boolean isIntegerParseInt(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException nfe) {}
        return false;
    }

    public static boolean isIntegerRegex(String str) {
        return str.matches("^[0-9]+$");
    }

    public static void main(String[] args) {
        long starttime, endtime;
        int iterations = 1000000;
        starttime = System.currentTimeMillis();
        for (int i=0; i<iterations; i++) {
            isIntegerParseInt("123");
            isIntegerParseInt("not an int");
            isIntegerParseInt("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation took " + (endtime - starttime) + " ms.");
        starttime = System.currentTimeMillis();
        for (int i=0; i<iterations; i++) {
            isIntegerRegex("123");
            isIntegerRegex("not an int");
            isIntegerRegex("-321");
        }
        endtime = System.currentTimeMillis();
        System.out.println("This operation took " + (endtime - starttime) + " ms.");
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您的正则表达式将拒绝负数,而parseInt方法将接受它们.

  • 我的理解是你应该只编译一次正则表达式,然后调用pattern.matcher(s).matches().这应该比每次构建正则表达式更快.此外,根据输入字符串,您的测试可能会有不同的行为.如果大多数时候你没有收到整数,我的猜测是正则表达式应该更快. (7认同)