我使用 NHibernate 用两种方法编写相同的查询:
1- 通过使用 HQL
如下所示
public long RetrieveHQLCount<T>(string propertyName, object propertyValue)
{
using (ISession session = m_SessionFactory.OpenSession())
{
long r = Convert.ToInt64(session.CreateQuery("select count(o) from " + typeof(T).Name + " as o" + " where o." + propertyName + " like '" + propertyValue + "%'").UniqueResult());
return r;
}
}
2- 通过使用 ICriteria
和 SetProjections
如下
public long RetrieveCount<T>(string propertyName, object propertyValue)
{
using (ISession session = m_SessionFactory.OpenSession())
{
// Create a criteria object with the specified criteria
ICriteria criteria = session.CreateCriteria(typeof(T));
criteria.Add(Expression.InsensitiveLike(propertyName, propertyValue))
.SetProjection(Projections.Count(propertyName));
long count = Convert.ToInt64(criteria.UniqueResult());
// Set return value
return count;
}
}
现在我的问题是哪一个性能更好?为什么?
最佳答案
我认为获得更好指标的最佳方法是如此处所述。去下载 nhProf 并对其进行分析。
如果您想要更多详细信息,请获取生成的 SQL,然后通过 SQL Server Profiler 运行它,以更好地了解它正在做什么。
但老实说,如果数据库中有任何数量的数据,那么执行 LIKE 查询将会给你带来可怕的结果。
我强烈建议您在 SQL Server 中设置全文索引,然后使用它:
在nHibernate中注册自由文本和包含函数。
与 ICriteria 查询集成的另一个很好的示例如下:
http://xlib.wordpress.com/2009/12/04/integrating-freetext-search-in-nhibernate-detached-criteria/
或者,您也可以使用 Lucene.NET 进行全文索引。
关于c# - 哪一款性能更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2780432/