Re: Executing the same query multiple times gets slow - Mailing list pgsql-jdbc

From Laurenz Albe
Subject Re: Executing the same query multiple times gets slow
Date
Msg-id 1b139ffdf4bf5d8d131483f9bfe3568dfc5bac03.camel@cybertec.at
Whole thread Raw
In response to Re: Executing the same query multiple times gets slow  (Blake McBride <blake1024@gmail.com>)
List pgsql-jdbc
On Sat, 2023-07-22 at 10:25 -0500, Blake McBride wrote:
> I have narrowed the problem down quite a bit.  Here is what I found:
>
> 1.  My original select was in error.  I fixed it.  Same problem.
>
> 2.  If I do not use a prepared statement, it is fast all of the time.  If I use a prepared
>     statement it runs fast most of the time and then after repeated use starts getting
>     really slow as I previously reported.
>
> For me, in this instance, the solution is to not use a prepared statement.
>
> In my opinion, this is a major flaw in either PostgreSQL or the JDBC driver.
> My application has 10,000 Java classes and uses prepared statements everywhere.  
>
> My solution in this instance will not work generally because there is too much
> code to test and adjust.  It is unreasonable for prepared statements to work this
> significantly slower.
>
> In my opinion, this is a huge problem and should be top priority.

There is an alternative to blindly disabling PostgreSQL's use of a generic plan:
you could examine the generic plan and try to improve it.

In PostgreSQL v16, you can use

  EXPLAIN (GENERIC_PLAN) SELECT /* query with $1, $2 etc. as parameters */

to get the generic plan.  With older versions, you can (using the appropriate
number and type for the parameters)

  PREPARE stmt(integer,text) AS SELECT /* query with $1, $2 etc. as parameters */
  EXPLAIN (ANALYZE, BUFFERS) stmt(1, 'something');

Repeat the EXECUTE at least 5 times, until PostgreSQL switches to the generic plan.

Then you can analyze why the generic plan is so slow.  It is often possible to
improve PostgreSQL's estimates to either make it pick a better generic plan or
to make it *not* switch to a generic plan by itself.  Ask for help if you cannot
do that alone.

That way, you don't have to disable generic plans.

Yours,
Laurenz Albe



pgsql-jdbc by date:

Previous
From: Dave Cramer
Date:
Subject: Re: Executing the same query multiple times gets slow
Next
From: Pawel Veselov
Date:
Subject: PGConnection.getNotifications(0) doesn't block