C # 및 Sql Server 2008을 사용하여 ASP.NET 프로젝트에서 작업하고 있습니다.
세 개의 테이블이 있습니다.
각 사용자는 각 데이터 필드에 대한 특정 값을 가지며이 값은 DataFieldsValues에 저장됩니다.
이제 다음과 같은 보고서를 표시하려고합니다.
나는 개체를 만든 User
, 및 DataField
. DataField 개체 string GetValue(User user)
에는 특정 사용자에 대한 필드 값을 가져 오는 Method가 있습니다.
그런 다음 사용자 List<User> users
목록과 DataField 목록 List<DataField> fields
이 있고 다음을 수행합니다.
string html = string.Empty;
html += "<table>";
html += "<tr><th>Username</th>";
foreach (DataField f in fields)
{
html += "<th>" + f.Name + "</th>";
}
html += "</tr>"
foreach (User u in users)
{
html += "<tr><td>" + u.Username + "</td>"
foreach (DataField f in fields)
{
html += "<td>" + f.GetValue(u) + "</td>";
}
html += "</tr>"
}
Response.Write(html);
이것은 잘 작동하지만 매우 느리며 20 명의 사용자와 10 개의 데이터 필드에 대해 이야기하고 있습니다. 이를 달성하기 위해 성능면에서 더 좋은 방법이 있습니까?
편집 : 클래스 내의 각 매개 변수에 대해 다음 방법을 사용하여 값을 검색합니다.
public static string GetDataFromDB(string query)
{
string return_value = string.Empty;
SqlConnection sql_conn;
sql_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXXX"].ToString());
sql_conn.Open();
SqlCommand com = new SqlCommand(query, sql_conn);
//if (com.ExecuteScalar() != null)
try
{
return_value = com.ExecuteScalar().ToString();
}
catch (Exception x)
{
}
sql_conn.Close();
return return_value;
}
예를 들면 :
public User(int _Id)
{
this.Id = _Id
this.Username = DBAccess.GetDataFromDB("select Username from Users where Id=" + this.Id)
//...
}
여기에 도움이 될 두 가지 제안이 있습니다. 첫 번째 제안은 성능을 크게 향상시킬 수있는 것입니다. 두 번째 제안도 도움이 될 수 있지만 귀하의 경우 앱이 더 빨라지지는 않습니다.
메서드를 GetDataFromDB(string query)
매우 자주 호출합니다 . 매번 새로운 SqlConnection 및 SqlCommand를 생성하기 때문에 이것은 좋지 않습니다. 이것은 시간과 자원이 필요합니다. 또한 네트워크 지연이있는 경우에는이를 호출하는 수를 곱합니다. 그래서 그것은 단지 나쁜 생각입니다.
이 메서드를 한 번 호출하고 a와 같은 컬렉션을 채우면 Dictionary<int, string>
사용자 ID 키에서 사용자 이름 값을 빠르게 찾을 수 있습니다.
이렇게 :
// In the DataField class, have this code.
// This method will query the database for all usernames and user ids and
// return a Dictionary<int, string> where the key is the Id and the value is the
// username. Make this a global variable within the DataField class.
Dictionary<int, string> usernameDict = GetDataFromDB("select id, username from Users");
// Then in the GetValue(int userId) method, do this:
public string GetValue(int userId)
{
// Add some error handling and whatnot.
// And a better name for this method is GetUsername(int userId)
return this.usernameDict[userId];
}
이 경우에는 조금이라도 개선 할 수있는 또 다른 방법이 있습니다 StringBuilder
. 수업을 사용하세요 . 상당한 성능 향상이 있습니다 (개요 : http://support.microsoft.com/kb/306822 ).
SringBuilder sb = new StringBuilder();
sb.Append("<table><tr><th>Username</th>");
foreach (DataField f in fields)
{
sb.Append("<th>" + f.Name + "</th>");
}
// Then, when you need the string
string html = sb.ToString();
좀 더 설명이 필요하면 알려주세요.하지만 요청하신 내용은 매우 가능합니다. 우리는 이것을 해결할 수 있습니다!
이 두 가지 간단한 변경을 수행하면 뛰어난 성능을 얻을 수 있습니다. 보증합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다