【发布时间】:2021-07-25 14:22:15
【问题描述】:
我的任务是修复一些代码。每次程序运行时,它都会变得越来越慢。通过使用一些断点和分析,我认为我缩小了它背后的原因,但是我不确定如何解决它。
这个函数使用了大量的 cpu,我将它缩小到我的现有客户端变量,该变量无限期地添加 https://gyazo.com/67e44844a279a10e1b11165b941b1cf6
public void AddNewClientData()
{
Logger logger = LogManager.GetCurrentClassLogger();
try {
string[] fileLines = File.ReadAllLines("ClientList.csv");
foreach(string line in fileLines)
{
string[] lineParts = line.Split(',');
Client client = new Client()
{
ClientName = lineParts[0],
ClientPhone = lineParts[1],
EntryTime = DateTime.Parse(lineParts[2]),
ExitTime = DateTime.Parse(lineParts[3])
};
bool clientExists = false;
// Check that the user does not already exist
string sqlGet = "Select * FROM ClientInOut";
using(var connection = Helpers.GetConnection())
{
connection.Open();
List < Client > existingClients = connection.Query<Client>(sqlGet).ToList();
for (int i = 0; i < fileLines.Length; i++)
{
foreach(Client existingCustomer in existingClients)
{
if (existingCustomer == client) {
clientExists = true;
}
}
}
}
// add the new client
if (clientExists == false) {
string sql =
"INSERT INTO ClientInOut (ClientName, ClientPhone, EntryTime, ExitTime) Values (@ClientName, @ClientPhone, @EntryTime, @ExitTime);";
using(var connection = Helpers.GetConnection())
{
connection.Open();
var affectedRows = connection.Execute(sql, client);
}
}
}
}
【问题讨论】:
-
我猜
existingCustomer == client每次都会返回false。也许你应该重写Client.Equals函数,所以它比较字段而不是对象本身,并像existingCustomer.Equals(client)一样使用它 -
我想我会使用散列并将其沿客户端字段存储到数据库中。然后使用该哈希进行查询,而不是查询完整列表并进行迭代。
-
我看到一个非常不必要的嵌套 foreach() 循环,无论如何都应该在 SQL 中找到现有客户。
标签: c# sql visual-studio