1

假设我有一个用于在 Web 应用程序上导航的类别列表。我是否应该在 global.asax 的 application_onStart 中添加一个函数调用,而不是从数据库中为每个用户进行选择,以将该数据提取到一个数组或集合中,以便一遍又一遍地重复使用。如果我的数据根本没有改变 - (编辑 - 经常),这会是最好的方法吗?

4

8 回答 8

2

过早的优化是邪恶的。这是给定的,如果您在应用程序中遇到性能问题并且您想要向用户显示“静态”信息,您绝对可以将该数据加载到数组中并将其存储在应用程序对象中。您需要小心并平衡内存使用与优化。

您遇到的问题是更改数据库存储的信息而不是让它更新缓存的版本。您可能希望在数据库中存储某种最后更改日期,并将其与缓存数据一起存储在状态中。这样您就可以查询最大更改时间并进行比较。如果它比您的缓存日期更新,那么您将其转储并重新加载。

于 2008-09-15T16:18:54.013 回答
2

您可以将列表项存储在 Application 对象中。你是对的application_onStart(),只需调用一个方法来读取你的数据库并将数据加载到 Application 对象。

在 Global.asax

public class Global : System.Web.HttpApplication
{
    // The key to use in the rest of the web site to retrieve the list
    public const string ListItemKey = "MyListItemKey";
    // a class to hold your actual values. This can be use with databinding
    public class NameValuePair
    { 
        public string Name{get;set;} 
        public string Value{get;set;}
        public NameValuePair(string Name, string Value)
        {
            this.Name = Name;
            this.Value = Value;
        }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        InitializeApplicationVariables();
    }


    protected void InitializeApplicationVariables()
    {
        List<NameValuePair> listItems = new List<NameValuePair>();
        // replace the following code with your data access code and fill in the collection
        listItems.Add( new NameValuePair("Item1", "1"));
        listItems.Add( new NameValuePair("Item2", "2"));
        listItems.Add( new NameValuePair("Item3", "3"));
        // load it in the application object
        Application[ListItemKey] = listItems;
    }
 }

现在您可以在项目的其余部分访问您的列表。例如,在 default.aspx 中加载 DropDownList 中的值:

<asp:DropDownList runat="server" ID="ddList" DataTextField="Name" DataValueField="Value"></asp:DropDownList>

在代码隐藏文件中:

protected override void OnPreInit(EventArgs e)
{
    ddList.DataSource = Application[Global.ListItemKey];
    ddList.DataBind();
    base.OnPreInit(e);
}
于 2008-09-15T17:17:08.010 回答
1

如果它永远不会改变,它可能不需要在数据库中。

如果数据不多,你可以把它放在 web.config 中,或者在你的代码中作为 en Enum 。

于 2008-09-15T16:13:59.953 回答
1

获取所有可能很昂贵。尝试惰性初始化,仅获取请求数据,然后将其存储在缓存变量中。

于 2008-09-15T16:16:53.753 回答
1

在应用程序变量中。

请记住,应用程序变量可以包含 .Net 中的对象,因此您可以在 global.asax 中实例化该对象,然后直接在代码中使用它。

由于应用程序变量在内存中,它们非常快(而不是必须调用数据库)

例如:

// Create and load the profile object
x_siteprofile thisprofile = new x_siteprofile(Server.MapPath(String.Concat(config.Path, "templates/")));
Application.Add("SiteProfileX", thisprofile);
于 2008-09-15T16:18:58.477 回答
1

我会将数据存储在应用程序缓存(缓存对象)中。而且我不会预加载它,我会在第一次请求时加载它。缓存的好处在于 ASP.NET 将对其进行管理,包括为您提供在文件更改、时间段等后使缓存条目过期的选项。由于项目保存在内存中,因此对象不会被序列化/反序列化,因此使用速度非常快。

用法很简单。Cache 对象上有 Get 和 Add 方法,分别用于检索和添加项目到缓存中。

于 2008-09-15T17:28:15.720 回答
0

我将静态集合用作私有集合,并使用公共静态属性从数据库加载或获取它。

此外,您可以添加一个静态日期时间,该日期时间在加载时设置,如果您调用它,经过一定的时间,清除静态集合并重新查询它。

于 2008-09-15T16:12:35.603 回答
0

缓存是要走的路。如果您喜欢设计模式,请查看单例。

但总的来说,在您注意到性能下降之前,我不确定我是否会担心它。

于 2008-09-15T17:31:28.927 回答