在我的程序中,我对数据库执行查询。大多数情况下,这些查询是固定的(即select * from table 1
),并由以下函数调用:
Table getTable1() {
return execQuery("select * from table1;");
}
在我写的函数中插入常量查询是否合适?或者创建包含这些查询的常量字符串是否更好?
const string queryTable1 = "select * from table1;";
Table getTable1() {
return execQuery(queryTable1);
}
答案 0 :(得分:0)
我可能会创建一个带参数的函数:
Table getTable(const std::string& tableName) {
return execQuery("select * from " + tableName + ";");
}
答案 1 :(得分:0)
据我所知,大多数编译器通过合并相等的字符串来优化程序。例如:
printf("asdf");
printf("asdf");
在这种情况下,程序可能会编译如下。 (我使用NASM)
push str
call _printf
add esp, 4
push str
call _printf
add esp, 4
str: db "asdf", 0
如果您使用const std::string
常量对象,而不是const char *
,我认为您的解决方案很好。
Table getTable()
{
static const string queryTable1 = "select * from table1";
return execQuery(queryTable1);
}
但请注意,如果getTable
是全局对象,则不应在全局对象的构造函数中使用queryTable1
。像我一样,使queryTable1
getTable
的静态常量。