title: Hibernate queries slow down drastically after an entity is loaded in the session
body: <p>I'm using Hibernate EntityManager, and am experiencing a weird slowdown in my Hibernate queries. Take a look at this code:</p>
  
  <pre><code>public void testQuerySpeed() {
      for(int i = 0; i &lt; 1000; i++) {
          em.createNativeQuery("SELECT 1").getResultList();
      }
  }
  </code></pre>
  
  <p>This runs in about 750ms on my machine. Not blazing fast considering it's just selecting a constant integer, but acceptable. My problem arises the moment ANY entities are loaded in my EntityManager session before I launch my query:</p>
  
  <pre><code>public void testQuerySpeed() {
      CommercialContact contact = em.find(CommercialContact.class, 1890871l);
  
      for(int i = 0; i &lt; 1000; i++) {
          em.createNativeQuery("SELECT 1").getSingleResult();
      }
  }
  </code></pre>
  
  <p>The em.find() is fast, but the runtime 1000 queries increased more than ten-fold, to about 10 seconds. If I put an <code>em.clear()</code> after the <code>em.find()</code>, the problem goes away again and runtime goes back to 750ms. </p>
  
  <p>I've used a native query here, but the problem exists with HQL queries as well. It seems ALL queries take at least 70ms whenever an entity is in the EntityManager session.</p>
  
  <p>This performance drop is really hurting us when generating lists where n+1 queries are needed.</p>
  
  <p>I've tested the latest Hibernate 3.5 beta, and have the exact same problem. Has anyone seen this problem, or any ideas on how to fix it?</p>
  
  <p>I'm using PostgreSQL 8.3, using resource local transactions (running in Tomcat). Using the built-in connection pool, but using C3P0 made no difference.</p>