我有一个类似下面的字符串:
{A}jahshs{b}jwuw{c}wuqjwhaha{d}{e}{f}jsj{g}
我需要替换每个{x}
为不同的字符串。问题在于这个过程将会每秒重复约1000次,所以我需要一种优化/快速的方法来完成它。
有任何想法吗?使用Boost replace?还是Boost format?等等。
预先分配所有缓冲区
....
获利
哦,不要垃圾邮件。样例代码在 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.239秒。 大约是每秒68k次扩展。
哎呀,在发布版中,它每秒可进行400万个扩展。在Coliru上几乎能达到每秒100万次的扩展。
有改进的空间:
'}'
来简化代码。expand
函数吗?正如你所看到的,它是一种“宏扩展器”。我确保你可以返回任何可以进行IO流操作的东西。也许这个2行编辑会有所帮助? - seheinsert_expanded
接受构建器流而更加高效(http://coliru.stacked-crooked.com/a/be82fad7b1442787)轻松实现。一个模仿邮件合并的示例:http://coliru.stacked-crooked.com/a/cde6e91f3d898888 - sehe
std::string::replace
,测量并证明它不够快? - Kerrek SB