首页 > 解决方案 > 为什么 C++ 正则表达式这么慢?

问题描述

我是 C++ 新手,必须处理一个文本文件。我决定用正则表达式来做这件事。我想出的正则表达式:

(([^\\s^=]+)\\s*=\\s*)?\"?([^\"^\\s^;]+)\"?\\s*;[!?](\\w+)\\s*

我根据以下帖子编写了我的 C++ 代码:

c++ 正则表达式使用 regex_search() 提取所有子字符串

这是 C++ 代码:

#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <chrono>
#include <iterator>

void print(std::smatch match)
{
}

int main()
{
    std::ifstream file{ "D:\\File.txt" };
    std::string fileData{};

    file.seekg(0, std::ios::end);
    fileData.reserve(file.tellg());
    file.seekg(0, std::ios::beg);

    fileData.assign(std::istreambuf_iterator<char>(file), 
    std::istreambuf_iterator<char>());

    static const std::string pattern{ "(([^\\s^=]+)\\s*=\\s*)?\"? 
    ([^\"^\\s^;]+)\"?\\s*;[!?](\\w+)\\s*" };
    std::regex reg{ pattern };
    std::sregex_iterator iter(fileData.begin(), fileData.end(), reg);
    std::sregex_iterator end;

    const auto before = std::chrono::high_resolution_clock::now();

    std::for_each(iter, end, print);

    const auto after = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> delta = after - before;
    std::cout << delta.count() << "ms\n";

    file.close();
}

我正在处理的文件包含 541 行。上面的程序需要 5 SECONDS 才能获得所有 507 个匹配项。我以前在 C# 中做过这样的事情,而且从来没有这么慢的正则表达式。所以我在 C# 中尝试了同样的事情:

var filedata = File.ReadAllText("D:\\File.txt", Encoding.Default);

const string regexPattern = 
    "(([^\\s^=]+)\\s*=\\s*)?\"?([^\"^\\s^;]+)\"?\\s*;[!?](\\w+)\\s*";

var regex = new Regex(regexPattern, RegexOptions.Multiline |      
    RegexOptions.Compiled );
    var matches = regex.Matches(filedata);

foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}

只需 500 MILLISECONDS 即可找到所有 507 个匹配项 + 在控制台上打印它。因为我必须使用 C++,所以我需要更快。

如何让我的 C++ 程序更快?我做错了什么?

标签: c++regex

解决方案


我提到了 C 风格的字符串,但我并不是说尽可能多地使用纯 C 风格可以提高正则表达式的性能。我的意思很简单,我们应该能够在编译时做更多的事情,而std::string在运行时做更少的操作,这样我们就可以获得更好的性能。

原始答案

如您所知,我们有两种类型的字符串:C 风格的字符串和std::string.

std::string可以在我们编码时使用,但我们可以说它是一种沉重的东西(这就是为什么有些人不喜欢它的原因)。首先,std::string使用堆内存意味着它使用newmalloc;其次,std::string在其大小增加的同时使用某种特定的算法(将当前大小加倍并将当前内容移动到新的内存区域并释放旧的)。这些会导致性能问题。

正则表达式显然都是关于字符串的,它需要到处使用字符串。std::regex玩了很多std::string,这就是为什么性能std::regex不好。

此外,std::string完全是运行时的东西。例如,您可以在编译时初始化 C 风格的字符串,但不能std::string在编译时初始化 a。这意味着关于的东西std::string很少在编译时进行优化。这是一个关于我们如何利用编译时间在运行时获得非常好的性能的示例:为什么使用 constexpr 在运行时而不是在编译时评估变量的初始化

std::regex在编译时不能做很多事情,因为它使用std::string,这也可能导致性能问题。这就是人们可能喜欢 CTRE(编译时正则表达式)库的原因。

如果std::string_view可以在源代码中使用std::regex,我认为性能会更好。

C++ 承诺:“不要为不使用的东西付费。” 没有冒犯任何人,但我个人认为这std::regex违背了承诺。如果 C++ 标准委员会认为功能比其他任何事情都重要,我会说为什么不使用 Java。


推荐阅读