我有一个 C# 应用程序,其中我遇到了这个问题:当我运行这个片段时:
第一种方式
public void GetList(List<string> liste, List<int> outliste)
{
foreach( string s in liste){
outliste.Add(SqlFunction(s));
}
}
public int SqlFunction(string str)
{
string query = "select id from user where name="+str;
...................
// return the id
}
执行时间为51秒
第二种方式
public void SqlSecondWayFunction(List<string> liste, List<int> outliste)
{
string query ="select id from user where (";
foreach(string str in liste){
query += "name=" str + "or ";
}
query += " 1=0 )";
...................
// fill outliste by the result of the query
}
执行时间是1m:19sec!!!!!!!!! (liste 的计数约为 11000)。
所以我需要知道为什么第一种方式更快?
请您参考如下方法:
第一个更快,因为它做的事情更少。而且它只选择记录的一个子集。
第二个速度较慢,因为您要连接大量字符串(这做起来相当慢),并且对数据库中的每个 记录执行数千次不必要的比较,只是为了返回 无论如何记录。
基本上,您要求数据库将 name 列与表中每条记录的 11,000 个字符串进行比较。例如,如果表包含 100,000 条记录,那么您将进行 1,100,000,000 字符串比较。然后您无论如何都会返回所有记录,因为您的条件之一是“1 = 1”,始终为真。
