调整std::字符串大小的最快方法是什么

What is the fastest way to resize std::string?

本文关键字:方法 是什么 std 字符串 调整      更新时间:2023-10-16

我正在处理一个C++项目(使用VS2008(,在该项目中,我需要从一个文件将一个非常大的XML文件加载到std::wstring中。目前,以下行在加载数据之前保留内存:

//std::wstring str;
//size_t ncbDataSz = file size in bytes
str.resize(ncbDataSz / sizeof(WCHAR));

但我目前的问题是,对于较大的字符串大小,resize方法需要较长的时间(我刚刚在x64项目中,在具有12GB空闲RAM的台式电脑上用3GB的数据对其进行了测试,大约需要4-5秒才能完成。(

所以我很好奇,有没有一种更快(更优化(的方法来调整std::string的大小?我只要求Windows。

您可以用char_traits实例化basic_string,它对assign(count(不起任何作用:

#include <string>
struct noinit_char_traits : std::char_traits<char> {
    using std::char_traits<char>::assign;
    static char_type* assign(char_type* p, std::size_t count, char_type a) { return p; }
};
using noinit_string = std::basic_string<char, noinit_char_traits>;

请注意,它还将影响basic_string::fill((等函数。

您可以使用std::string::reserve来分配输入字符串,而不是调整输入字符串的大小,因为调整大小还会初始化每个元素。

你可以试试这样的东西,看看它是否能提高你的性能:

std::wstring load_file(std::string const& filename)
{
    std::wifstream ifs(filename, std::ios::ate);
    // errno works on POSIX systems not sure about windows
    if(!ifs)
        throw std::runtime_error(std::strerror(errno));
    std::wstring s;
    s.reserve(ifs.tellg()); // allocate but don't initialize
    ifs.seekg(0);
    wchar_t buf[4096];
    while(ifs.read(buf, sizeof(buf)/sizeof(buf[0])))
        s.append(buf, buf + ifs.gcount()); // this will never reallocate
    return s;
}