简体   繁体   English

哪个更快:DateTime.TryParse或Regex

[英]Which is Quicker: DateTime.TryParse or Regex

In .NET, to determine whether a supplied string is a date, which one is quicker: using DateTime to cast it to a date, or using a regular expression to check the string for its validity as a date? 在.NET中,要确定提供的字符串是否是日期,哪个更快:使用DateTime将其转换为日期,还是使用正则表达式来检查字符串作为日期的有效性?

I just need to ensure the value supplied is a date, and I'm not doing anything with it afterward. 我只需要确保提供的值是一个日期,之后就不对其进行任何操作。

Thanks. 谢谢。

My first question would be which is more expressive? 我的第一个问题是哪个更具表现力? Or Which is the most readable? 或哪个是最易读的? In a case like this where performance gains would probably be negligible, I'd vote for the code that's the easiest to maintain/read. 在这种情况下,性能提升可能微不足道,在这种情况下,我会选择最易于维护/阅读的代码。

EDIT 编辑

Found a decent, similar post. 找到了一个体面的类似职位。 It's worth a read 值得一读

Regex vs Tryparse what is the best in performance 正则表达式与Tryparse性能最佳

A good regex should be much faster, and maybe consume less transient memory. 一个好的正则表达式应该更快,并且可能消耗更少的瞬时内存。

But here's the flipside of the coin: 但是,这是硬币的另一面:

You're pretty-much tied to only one time format, which means that internationalization will be painful, and that your users need to be educated to enter the date in the proper format. 您几乎只限于一种时间格式,这意味着国际化将是痛苦的,并且需要教育您的用户以正确的格式输入日期。

Also, you will lose some date validation, say, how do you weed-out Feb 29th on non leap-years? 另外,您将丢失一些日期验证,例如,如何在2月29日非leap年淘汰? April 31st? 4月31日?

The best thing to do would be to write a bit of test code for both and then run a loop to do it a million times. 最好的办法是为两者编写一点测试代码,然后运行一个循环以执行一百万次。 Without knowing the input, it would be hard to answer this (although my guess would be that TryParse would be quicker). 在不知道输入的情况下,很难回答这个问题(尽管我猜想TryParse会更快)。

That said, the time difference on today's processors is probably irrelevant. 也就是说,当今处理器的时差可能无关紧要。

UPDATE: When run in a fiddle TryParse is a lot quicker. 更新:当一个小提琴运行的TryParse是快了很多

I ran a rudimentary test with 10000 items. 我对10000个项目进行了基本测试。 It looks like Regexp is at least twice as fast as DateTime.Parse. 看起来Regexp的速度至少是DateTime.Parse的两倍。 See for yourself with the code below: 自己看下面的代码:

    private string[] arrDates = new string[10000];

    protected void Page_Load(object sender, EventArgs e)
    {
        initialise();

        RunRegexDemo();
        RunDateTimeParseDemo();

    }

    private void initialise()
    {
        Random ryear, rmonth, rdate;
        ryear = new Random();
        rmonth = new Random();
        rdate = new Random();
        int y, m, d;


        DateTime dt;

        for (int i = 0; i < arrDates.Length; i++)
        {
            y = 0;
            m = 0;
            d = 0;

            while (y < 1850)
            {
                y = ryear.Next(2050);
            }
            while (m < 1 || m > 12)
            {
                m = rmonth.Next(12);
            }
            while (d < 1 || d > 28)
            {
                d = rdate.Next(28);
            }

            dt = new DateTime(y, m, d);

            arrDates[i] = dt.ToString("yyyy-MM-dd");

            //lbl1.Text += "<br />" + arrDates[i];
        }

    }

    private void RunRegexDemo()
    {
        System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
        lbl1.Text+= "<h4>Starting Regex demo</h4>";
        string f;

        st.Start();

        foreach(string x in arrDates){
            f= "<br/>" + x + " is a valid date? = " + System.Text.RegularExpressions.Regex.IsMatch(x, @"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$");
        }

        st.Stop();
        lbl1.Text+= "<p>Ended RegEx demo. Elapsed time: " + st.ElapsedMilliseconds;
    }


    protected void RunDateTimeParseDemo(){
        System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
        lbl1.Text += "<h4>Starting DateTime.Parse demo</h4>";
        st.Start();
        DateTime dt;
        string f;
        foreach (string x in arrDates)
        {
            f = "<br/>" + x + " is a valid date? = " + DateTime.TryParse(x, out dt);
        }

        st.Stop();
        lbl1.Text += "<p>Ended TryParse demo. Elapsed time: " + st.ElapsedMilliseconds;
    }

在这种情况下,正则表达式似乎更快,因为正则表达式将仅查找模式,因为DateTime解析将需要查找模式以及从该模式中获取值以创建DateTime对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM