繁体   English   中英

快速多次替换为字符串

[英]Fast multi-replacement into string

我有一个像下面这样的字符串:

{A}jahshs{b}jwuw{c}wuqjwhaha{d}{e}{f}jsj{g}

我需要用不同的字符串替换每个{x} 问题来了,因为这个过程将重复大约1000次/秒,所以我需要一种优化/快速的方法来完成它。

任何想法? 提升替换? 提升格式? 等等..

  1. 预分配所有缓冲区

    ....

  2. 利润

哦,不要垃圾邮件。 示例代码 5 10分钟。

好的,这里也是: Live On Coliru

#include <string>
#include <sstream>
#include <boost/utility/string_ref.hpp>

template <typename Range>
int expand(Range const& /*key*/)
{
    return rand()%42; // todo lookup value with key (be sure to stay lean here)
}

#include <iostream>
int main()
{
    static const std::string msg_template = "{A}jahshs{b}jwuw{c}wuqjwhaha{d}{e}{f}jsj{g}\n";

    std::ostringstream builder;
    builder.str().reserve(1024); // reserve ample room, not crucial since we reuse it anyways

    for (size_t iterations = 1ul << 14; iterations; --iterations)
    {
        builder.str("");
        std::ostreambuf_iterator<char> out(builder);

        for(auto f(msg_template.begin()), l(msg_template.end()); f != l;)
        {
            switch(*f)
            {
                case '{' : 
                    {
                        auto s = ++f;
                        size_t n = 0;

                        while (f!=l && *f != '}')
                            ++f, ++n;

                        // key is [s,f] now
                        builder << expand(boost::string_ref(&*s, n));

                        if (f!=l)
                            ++f; // skip '}'
                    }
                    break;
                default:
                    *out++ = *f++;
            }
        }
        // to make it slow, uncomment:
        // std::cout << builder.str();
    }
}

这在我的系统上运行~0.239s。 那是每秒约68,000次扩展 哎呀。 发布版本中,它可以进行400万次扩展/秒。 Coliru,它达到近100万次扩展/秒

改进空间:

  • 您可以预先验证输入
  • 如果你知道参数键总是1个字母,那么你可以简单地用string替换string_ref,而不是循环'}'
  • 你可以预先计算论证的指标并向前跳。 这里的好处并不那么确定(顺序内存访问在某些处理器上非常好,而天真的方法可能更快)

暂无
暂无

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

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