您的位置:首页 > 数据库

数据库性能提升之减少访问数据库次数

2007-10-15 14:18 513 查看
前面两个方法我们通过调用ProductsBLL类的GetProductsByCategoryID(categoryID)方法来获取当前 category的product(第一种通过ObjectDataSource,第二种通过GetProductsInCategory (categoryID)).每次方法被调用时,BLL调用DAL,DAL通过SQL查询数据库,返回特定的记录.

如果有N个category,这个方法会访问数据库N+1次— 一次返回所有的category,N次返回特定category下的product.然而我们可以通过访问数据库两次来获取所有需要的数据— 一次返回所有的category,一次返回所有的product.一旦我们得到所有的product,我们可以根据CategoryID来过滤,然后再绑 定.

我们只需要稍微修改ASP.NET页的code-behind里的GetProductsInCategory(categoryID)方法来实现这个功能.我们首先来返回所有的product,然后根据传入的CategoryID里过滤.

private Northwind.ProductsDataTable allProducts = null;

protected Northwind.ProductsDataTable GetProductsInCategory(int categoryID)

...{


// First, see if we've yet to have accessed all of the product information


if (allProducts == null)




...{


ProductsBLL productAPI = new ProductsBLL();


allProducts = productAPI.GetProducts();


}


// Return the filtered view


allProducts.DefaultView.RowFilter = "CategoryID = " + categoryID;


return allProducts;


}

注意allProducts变量.它在第一次调用GetProductsInCategory(categoryID)时返回所有 product信息.确定allProducts对象被创建后,在根据CategoryID来对DataTable过滤.这个方法将访问数据库的次数从N +1减少到2次.

这个改进没有修改页面的声明语言.仅仅只是减少了数据库的访问次数.

注意:可能想当然的觉得减少了数据库访问次数会提高性能.但是这个不一定.如果你有大量的categoryID为NULL的product,这样使 用GetProducts方法返回的product有一部分不会被显示.而且如果你只需要显示一部分category的proudct(分页时就是这 样),而返回所有的product,这样对资源也是一种浪费.

通常对两种技术进行性能分析,唯一正确的方法是设置程序常见的场景来进行压力测试.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: