我正在使用C#和Sql Server 2008开发ASP.NET项目。
我有三个表:
每个用户对每个数据字段都有一个特定的值,并且该值存储在DataFieldsValues中。
现在,我想显示一个如下所示的报告:
我创建了对象User
和DataField
。在DataField对象中,存在Method string GetValue(User user)
,在其中我为特定用户获取字段的值。
然后,我有用户List<User> users
的列表和DataFields 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)
//...
}
最佳答案
这里有2条建议会有所帮助。第一个建议是什么将显着改善您的表现。第二条建议也有帮助,尽管可能无法使您的应用程序更快。
建议1
您经常调用GetDataFromDB(string query)
方法。这很不好,因为您每次都创建一个新的SqlConnection和SqlCommand。这需要时间和资源。同样,如果有任何网络延迟,则将其乘以您所拨打的电话数。因此,这是一个坏主意。
我建议您一次调用该方法,并让它填充一个类似于Dictionary<int, string>
的集合,以便您可以从用户ID key 快速查找您的Username值。
像这样:
// 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];
}
建议2这是您可以改进的另一种方法,尽管在这种情况下稍有改进-使用
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();
让我知道是否需要更多说明,但是您要求的是可行的。我们可以解决这个问题!如果您进行这两个简单的更改,您将获得出色的性能。我保证