Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么DateTime.Parse这么慢?_C#_.net_Datetime - Fatal编程技术网

C# 为什么DateTime.Parse这么慢?

C# 为什么DateTime.Parse这么慢?,c#,.net,datetime,C#,.net,Datetime,我对DateTime.Parse的速度如此之慢感到震惊。 这段代码运行大约需要100秒;如果我使用regex版本,需要100毫秒。 这是怎么回事 Stopwatch sw = new Stopwatch(); sw.Start(); var re = new Regex(@"(\d\d)/(\d\d)/(\d\d\d\d) (\d\d):(\d\d):(\d\d)", RegexOptions.Compiled); for (int i = 0; i < 100000; i++) {

我对DateTime.Parse的速度如此之慢感到震惊。 这段代码运行大约需要100秒;如果我使用regex版本,需要100毫秒。 这是怎么回事

Stopwatch sw = new Stopwatch();
sw.Start();
var re = new Regex(@"(\d\d)/(\d\d)/(\d\d\d\d) (\d\d):(\d\d):(\d\d)", RegexOptions.Compiled);
for (int i = 0; i < 100000; i++)
{
    //var m = re.Match("08/01/2012 23:10:12");
    DateTime.Parse("08/01/2012 23:10:12", CultureInfo.CreateSpecificCulture("en-US"));
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Stopwatch sw=新秒表();
sw.Start();
var re=new Regex(@“(\d\d)/(\d\d)/(\d\d\d)(\d\d):(\d\d):(\d\d)”,RegexOptions.Compiled);
对于(int i=0;i<100000;i++)
{
//var m=重新匹配(“08/01/2012 23:10:12”);
DateTime.Parse(“08/01/2012 23:10:12”,CultureInfo.CreateSpecificCulture(“美国”);
}
sw.Stop();
控制台写入线(软件延迟毫秒);
编辑:标记是正确的,将
CultureInfo.CreateSpecificCulture(“en-US”)
移动到循环之外有助于提高效率。我以前没有这样做的原因是我用VS Profiler分析了这段代码,它显示了以下结果:

这不是一个公平的测试

  • 调用
    CultureInfo.CreateSpecificCulture(“en-US”)
    是缓慢的部分。将其移出循环,存储结果并重用

  • 正则表达式只处理一种特定格式,但
    DateTime.Parse
    可以处理多种不同的输入格式。它必须决定它所理解的许多格式中哪一种是正确的。如果您事先知道格式是什么,那么就用它代替
    DateTime.Parse

  • 固定代码如下:

    CultureInfo ci = CultureInfo.CreateSpecificCulture("en-US");
    for (int i = 0; i < 100000; i++)
    {
        DateTime.ParseExact("08/01/2012 23:10:12", "MM/dd/yyyy HH:mm:ss", ci);
    }
    
    CultureInfo ci=CultureInfo.CreateSpecificCulture(“en-US”);
    对于(int i=0;i<100000;i++)
    {
    DateTime.ParseExact(“08/01/2012 23:10:12”,“MM/dd/yyyy HH:MM:ss”,ci);
    }
    
    通过这两个更改,我发现
    DateTime.ParseExact
    和正则表达式方法几乎相同


    正则表达式接受一些无效的日期时间,例如
    00/00/0000 99:99:99
    。如果你修改它,使它只接受有效的日期时间,它会变慢。

    ooh,我觉得很愚蠢,实际上将
    CreateSpecificCulture
    移出循环固定性能。我以前没有这么做的原因是因为我使用了VS Profiler,它表明问题出在
    解析中,请参见编辑中的屏幕截图。我当然同意在这里使用正则表达式有点作弊,但我考虑改用它,因为我100%确定输入数据有效,性能更重要。