在使用 clearsilver去 渲染模板的时候,数据大了之后会明显慢很多,但是cs应该是非常高效的模板引擎,怎么会突然这么慢。
下面是cs的测试例子
#include <ClearSilver.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string.h>
#include <ctime>
using namespace std;
//从文件读入到string里
string readFileIntoString(const char* filename)
{
ifstream ifile(filename);
//将文件读入到ostringstream对象buf中
ostringstream buf;
char ch;
while(buf&&ifile.get(ch))
buf.put(ch);
//返回与流对象buf关联的字符
return buf.str();
}
int i = 1;
NEOERR *output(void *ctx, char *s)
{
string* x = (string*)ctx;
// *x = *x + s;
x->append(s);
return STATUS_OK;
}
int main()
{
printf("dssds\n");
const string htmlpath = "list_machine_error.html";
const string hdfpath = "list_machine_error.out";
clock_t time1 = clock();
string hdf_str = readFileIntoString(hdfpath.c_str() );
// printf("%s\n", hdf_str.c_str() );
clock_t time2 = clock();
printf("time1- %f\n", (double)(time2-time1) );
HDF* hdf;
CSPARSE* parse;
hdf_init(&hdf);
clock_t time3 = clock();
printf("time2- %f\n", (double)(time3-time2) );
hdf_read_string(hdf, hdf_str.c_str() );
clock_t time4 = clock();
printf("time3- %f\n", (double)(time4-time3) );
cs_init(&parse, hdf);
cs_parse_file(parse, htmlpath.c_str() );
clock_t time5 = clock();
printf("time4- %f\n", (double)(time5-time4) );
string result;
cs_render(parse, &result, output);
clock_t time6 = clock();
printf("time5- %f\n", (double)(time6-time5) );
// // printf("%s ", result.c_str() );
// string filepath2 = "my.html";
// ofstream fout2(filepath2.c_str() );
// fout2<<result<<endl;
}
发现慢在cs_render 函数内
发现output函数中字符串拼接使用的 + 号
这里就得说字符串拼接了,对于大量的字符串拼接最好使用 append或者+= 类似java中的StringBuffer。