这个函数要完成的任务是:
利用mysqlpp查询出结果集,然后遍历每一行记录,生成一个Domain对象,放到list中,最后返回一个Domain对象的list。
在做测试的时候,发现遍历一万条数据竟然需要3秒多……所以请大家帮忙把把脉,看应该如何优化:
完整的while循环,计时:3.338秒
注释掉第10行,计时:1.174秒
注释掉7-11行,计时:1.193秒
代码:
1. Connection* conn = ConnPool::getSingletonPtr()->getConn();
2. Query qr = conn->query(sql);
3. UseResult res = qr.use();
// 开始计时
4. while(Row row = res.fetch_row()) // 循环10000条记录
5. {
6. Domain obj;
7. for(int i=0; i<row.size(); i++)
8. {
9. // 调用Domain的成员函数,为Domain对象赋值
10. obj.setValue(res.fetch_field(i).name(), row[i]);
11. }
12. objList->push_back(obj);
13.}
// 结束计时
Domain类中定义这么一堆属性:
int procedureNo;
int index;
int employeeNo;
int procCount;
int state;
int procPermission;
int procDeadline;
int advanceAlert;
DateTime procTime;
int resultFlag;
string comment;
int flowDirection;
int isHideComment;
int isTrack;
DateTime arriveTime;
string preNodesJsonStr;
string nextNodesJsonStr;
string attachStr;
string employeeName;
DateTime employeeBirthDay;
上面第10行用到的成员函数定义如下(之所以用这个函数,是因为数据表中的字段名和Domain类的属性名并不一致)
void Domain::setValue(const char * colName, const Element& ele)
{
if(strcmp(colName,"column010") == 0)
procedureNo = ele;
else if(strcmp(colName,"column020") == 0)
index = ele;
else if(strcmp(colName,"column030") == 0)
employeeNo = ele;
else if(strcmp(colName,"column040") == 0)
procCount = ele;
else if(strcmp(colName,"column050") == 0)
state = ele;
else if(strcmp(colName,"column060") == 0)
procPermission = ele;
else if(strcmp(colName,"column070") == 0)
procDeadline = ele;
else if(strcmp(colName,"column080") == 0)
advanceAlert = ele;
else if(strcmp(colName,"column090") == 0)
procTime = ele;
else if(strcmp(colName,"column100") == 0)
resultFlag = ele;
else if(strcmp(colName,"column110") == 0)
comment = ele;
else if(strcmp(colName,"column120") == 0)
flowDirection = ele;
else if(strcmp(colName,"column130") == 0)
isHideComment = ele;
else if(strcmp(colName,"column140") == 0)
isTrack = ele;
else if(strcmp(colName,"column150") == 0)
arriveTime = ele;
else if(strcmp(colName,"column160") == 0)
preNodesJsonStr = ele;
else if(strcmp(colName,"column170") == 0)
nextNodesJsonStr = ele;
else if(strcmp(colName,"column180") == 0)
attachStr = ele;
else if(strcmp(colName,"column190") == 0)
employeeName = ele;
else if(strcmp(colName,"column200") == 0)
employeeBirthDay = ele;
}
判断太多了,去掉for循环,直接按查询中读取到的字段顺序给对象赋值,这样效率会有不少提高