isNumber(string)方法的最佳实现 [英] Best implementation for an isNumber(string) method

查看:95
本文介绍了isNumber(string)方法的最佳实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的有限经验,我参与了多个项目,这些项目具有某种字符串实用程序类,该类具有确定给定字符串是否为数字的方法。这个想法一直都是相同的,但是实现却有所不同。有人用try / catch包围解析尝试

In my limited experience, I've been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea has always been the same, however, the implementation has been different. Some surround a parse attempt with try/catch

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

和其他与正则表达式匹配的

and others match with regex

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

这些方法中的一种优于另一种吗?我个人更喜欢使用regex方法,因为它很简洁,但是如果在遍历例如数十万个字符串的列表时调用它,它会与par一样执行吗?

Is one of these methods better than the other? I personally prefer using the regex approach, as it's concise, but will it perform on par if called while iterating over, say, a list of a several hundred thousand strings?

注意:由于我是该站点的新手,所以我并不完全了解该社区Wiki业务,因此,如果属于该站点,请告诉我,我将很乐意将其迁移。

Note: As I'm kinda new to the site I don't fully understand this Community Wiki business, so if this belongs there let me know, and I'll gladly move it.

编辑:
利用所有TryParse建议,我将Asaph的基准测试代码(感谢出色的帖子!)移植到C#并添加了TryParse方法。看起来,TryParse胜出了。但是,尝试捕获方法花费了大量时间。在我看来我做错了什么!我还更新了正则表达式以处理负数和小数点。

With all the TryParse suggestions I ported Asaph's benchmark code (thanks for a great post!) to C# and added a TryParse method. And as it seems, the TryParse wins hands down. However, the try catch approach took a crazy amount of time. To the point of me thinking I did something wrong! I also updated regex to handle negatives and decimal points.

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

Results for updated, C# benchmark code:

00:00:51.7390000 for isIntegerParseInt
00:00:03.9110000 for isIntegerRegex
00:00:00.3500000 for isIntegerTryParse

使用情况:

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);
}


推荐答案

我刚刚在这两种方法的性能(在Macbook Pro OSX Leopard Java 6上)。 ParseInt更快。输出为:

I just ran some benchmarks on the performance of these 2 methods (On Macbook Pro OSX Leopard Java 6). ParseInt is faster. Here is the output:

This operation took 1562 ms.
This operation took 2251 ms.

这是我的基准代码:


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.");
    }
}

此外,请注意,您的正则表达式将拒绝负数,并且parseInt方法将接受它们。

Also, note that your regex will reject negative numbers and the parseInt method will accept them.

这篇关于isNumber(string)方法的最佳实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆