问题
In that simple case:
public class Person
{
public int Id {get;set;}
public int Name {get;set;}
}
- I need generate a Grid with paging and ordering
- My database has about 100k persons
What option has better performance :
1) Get all elemtents in the first time and after take advantage of NHibernate First Level Cache, example:
personRep.FindAll().OrderBy(s =>s.Name).AsPagination(pageNumber,pageSize);
Obs.: AsPagination is a extension method...
2) Get only the actual page from database, example:
public virtual IList<T> GetPaginedList(int __pageIndex, int __pageSize,out int __total)
{
var _rowCount = Session.CreateCriteria(typeof(T))
.SetProjection(Projections.RowCount()).FutureValue<Int32>();
var _results = Session.CreateCriteria(typeof(T))
.SetFirstResult(__pageIndex * __pageSize)
.SetMaxResults(__pageSize)
.Future<T>();
__total = _rowCount.Value;
return _results;
}
回答1:
The 2nd option would be the best fit.
It is useless to retrieve all instances in one go, when you (the user) perhaps doesn't even 'use' all those instances.
If the 'Person' class is a 'heavy' class with lots of associations, it would be even better to create a 'PersonView' class, which contains only the properties you want to show in the Grid.
You don't have to map that PersonView
class, you'll simply have to 'import' it, so that NHibernate knows of its existance.
Then, you create a query on the Person
class, and define that a AliasToBean Transformer
has to be used to convert the Person
instances to PersonView instances.
By doing so, NHibernate will be able to generate a query which only retrieves the necessary columns from the DB, and will populate PersonView
instances with it.
回答2:
Like many data retrieval performance questions, which of these is better will depend on the usage scenario.
Option 1 is better if the user is likely going to peruse through most or all of the pages before the data becomes too stale to be useful. It's also better in cases of relatively small total result sets (2-3 pages), and cases where the result set won't change much (i.e. pulling user permissions from a DB), allowing you to store the entire data set in memory long-term, increasing performance of future runs by eliminating the network round trip.
Option 2 is better for situations involving long data pages and/or total result sets, "wide" records, or data that changes often enough that locally caching it doesn't do much good. It spreads the cost of retrieving records across the use of the result set, to the degree needed to show them. Such "lazy-loading" of paged results does increase the overall time and overhead of getting records (because there are more round trips), but your users are far more likely to notice and complain about a ten-second turnaround time on their search results than a half-second per page.
来源:https://stackoverflow.com/questions/4137356/nhibernate-paging-performance-better-option