c++ - 快速移动 CString 到 std::string

标签 c++ string c++11 mfc

我在混合使用 CStringconst char*std::string(非 unicode)的代码库中工作,其中所有新代码都专门使用 std::string。我现在必须执行以下操作:

{
    CString tempstring;
    load_cstring_legacy_method(tempstring);
    stdstring = tempstring;
}

并担心性能。这些字符串是 DNA 序列,因此我们可以轻松地拥有 100 多个字符串,每个字符串约 300 万个字符。请注意,调整 load_cstring_legacy_method 不是一个选项。我做了一个快速测试:

// 3M
const int stringsize = 3000000;
const int repeat     = 1000;

std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now();
for ( int i  = 0; i < repeat; ++i ){
    CString cstring('A', stringsize);
    std::string stdstring(cstring); // Comment out
    cstring.Empty();
}
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startTime).count() << " ms" << std::endl;

并注释掉 std::string 得到 850 ms,赋值为 3600 ms。差异的幅度令人惊讶,所以我猜基准可能没有达到我的预期。假设有处罚,我有什么办法可以避免吗?

最佳答案

所以你的问题是使 std::string 构造更快?

在我的机器上,比较这个

std::string stdstring(cstring); // 4741 ms

我通过这种方式获得了更好的表现:

std::string stdstring(cstring, stringsize); // 3419 ms

或者如果 std::string 已经像您问题的第一部分所暗示的那样存在:

stdstring.assign(cstring, stringsize); // 3408 ms

关于c++ - 快速移动 CString 到 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961651/

相关文章:

c++ - 如何在字符串数组中存储更多数量的字符串

c++ - 为什么不能在新的初始化程序中省略数组大小?

c++ - 根据成员容器的大小专门化成员函数

c++ - 根据用户输入用字母填充 vector ,并将开始和结束放在四肢上

java - 为什么我们有非静态函数/方法?

c# - 慢正则表达式拆分

c++ - std::map - 如何更改键排序?

c++ - C++11 中原子变量的复制初始化

c++ - Ofstream 在 Ubuntu 上创建隐藏(?)文件(同时打开)

c - 读取字符串不起作用