NHibernate的 - 第一个查询是痛苦的缓慢 [英] NHibernate - first query is painfully slow
问题描述
CREATE TABLE测试
(
id bigserial NOT NULL,
text text,
CONSTRAINT test_pkey PRIMARY KEY(id)
)
类:
public class Test
{
public virtual int ID {get;组; }
public virtual string Text {get;组; }
}
public class TestMap:ClassMap< Test>
{
public TestMap()
{
Table(test);
Id(x => x.ID,id);
Map(x => x.Text,text);
$ b $ p
$ b 这是我查询数据库的方式:
pre $ using(ISession session = SessionBuilder.OpenSession())
{
Stopwatch s = new Stopwatch();
s.Start();
var result = session.QueryOver< Test>()。Where(test => test.Text ==aaa)。
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); //> 150ms
s.Restart();
var result2 = session.QueryOver< Test>()。where(test => test.Text ==bbb)。
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); //〜4ms
}
为什么第一个查询需要这么长时间?有没有办法加快速度?
在连接到数据库时通常会有开销,在这种情况下,您不会由于连接池,请参阅其他查询。基于你在那里的时间,我会说这是你看到的问题。
另外,确保你只会让你的会话工厂只有一次,并缓存它然后从那开放会话。我不认为你是基于你的时机跑步,但是一个足够小的配置也可以。
Database table (PostgreSQL) containing 10000 rows:
CREATE TABLE test
(
id bigserial NOT NULL,
text text,
CONSTRAINT test_pkey PRIMARY KEY (id)
)
Classes:
public class Test
{
public virtual int ID { get; set; }
public virtual string Text { get; set; }
}
public class TestMap : ClassMap<Test>
{
public TestMap()
{
Table("test");
Id(x => x.ID, "id");
Map(x => x.Text, "text");
}
}
Here is how I query database:
using (ISession session = SessionBuilder.OpenSession())
{
Stopwatch s = new Stopwatch();
s.Start();
var result = session.QueryOver<Test>().Where(test => test.Text == "aaa").List();
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // >150ms
s.Restart();
var result2 = session.QueryOver<Test>().Where(test => test.Text == "bbb").List();
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); // ~4ms
}
Why the first query takes so long? Is there a way to speed it up?
There's usually overhead with making a connection to a database in which case you will not see with other queries due to connection pooling. Based on the timings you have there, I would say that's the problem you are seeing.
Also, make sure that you are only making your session factory only once and caching it and then opening sessions from that. I don't think you are running into that based on your timing, but with a small enough configuration it could be that as well.
这篇关于NHibernate的 - 第一个查询是痛苦的缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!