[英]Fast multi-replacement into string
我有一个像下面这样的字符串:
{A}jahshs{b}jwuw{c}wuqjwhaha{d}{e}{f}jsj{g}
我需要用不同的字符串替换每个{x}
。 问题来了,因为这个过程将重复大约1000次/秒,所以我需要一种优化/快速的方法来完成它。
任何想法? 提升替换? 提升格式? 等等..
预分配所有缓冲区
....
利润
哦,不要垃圾邮件。 示例代码
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万次扩展/秒 。
改进空间:
'}'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.