[英]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.