Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1krljC-0007hn-Ae for pgsql-general@arkaria.postgresql.org; Tue, 22 Dec 2020 17:45:42 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1krljB-0007JZ-AU for pgsql-general@arkaria.postgresql.org; Tue, 22 Dec 2020 17:45:41 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1krlj9-0007JS-FP for pgsql-general@lists.postgresql.org; Tue, 22 Dec 2020 17:45:41 +0000 Received: from [64.147.123.24] (helo=wout1-smtp.messagingengine.com) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1krlj2-0005WH-2i for pgsql-general@postgresql.org; Tue, 22 Dec 2020 17:45:38 +0000 Received: from compute5.internal (compute5.nyi.internal [10.202.2.45]) by mailout.west.internal (Postfix) with ESMTP id 39DF1B11; Tue, 22 Dec 2020 12:45:20 -0500 (EST) Received: from imap2 ([10.202.2.52]) by compute5.internal (MEProxy); Tue, 22 Dec 2020 12:45:20 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=compiler.org; h= mime-version:message-id:in-reply-to:references:date:from:to:cc :subject:content-type; s=fm3; bh=VmT3rydSvRwdGfGw9AgHLlduhaLwLfj SvgdOHciXbvI=; b=KeeeBB8YRybHYRQZ9bST5DEscV/ubK8h//oPoevPlFwm760 23gpb5ZNRvNwfJjthiV2H2pE6QiWeDmz7NomP8sYjiWxxbHLsTqNLKXu/f+3zMXO kcAcMQrkTbzGV+YDfZF0OtBu7Y7Q6C27NrR9N2m66WAvKgLifFy8IOHzmUQev4tA 7tEJNltuPj5i6qOrsguiyeA/tksQl9arD7at5eUODoNe+7R8N3oh6djxtm+zjpyt 4voy2e5QzN4xiSd0l4i9rlowjyjKjbxB6DO0uNlGtORJzEeCaZoALLm/9Q6Wkcrl GJaZISPnk1KLtk3NeEZD3h4+LXkjAH8hdYctBJA== DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= messagingengine.com; h=cc:content-type:date:from:in-reply-to :message-id:mime-version:references:subject:to:x-me-proxy :x-me-proxy:x-me-sender:x-me-sender:x-sasl-enc; s=fm1; bh=VmT3ry dSvRwdGfGw9AgHLlduhaLwLfjSvgdOHciXbvI=; b=DVu2dRvNosxUP5W8DH4Onz +pFcMhoHoTE97olWjPCcHjlCd+xauKuV9mZWC4e21t++ibFnPJv6PgjT4MUxgigU vyr1Ivxg8Vodfp0J9oJ2pFcCj9ULG+iRM67vxYLFk4rh0IGzl5M/JMXyjA7FkAjE D0lEVJAv13e0WC9rhpVQR9013PYtpxds6/a7x196714ikBmPP0nCoaqat2Ls2tYl cdtkUIcq9voc7dY2vsl4FZh2biFkAYsToSYQ634QoiTPkY0DjDV9AWLLrwSHVmEW 9Vxyj9U4OKta9ZFjydJYErfkU67mZ8IbjmY2gy+eGs/e+dGzpu+HH4BqqhdWTBQQ == X-ME-Sender: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgedujedrvddtgedguddtiecutefuodetggdotefrod ftvfcurfhrohhfihhlvgemucfhrghsthforghilhdpqfgfvfdpuffrtefokffrpgfnqfgh necuuegrihhlohhuthemuceftddtnecusecvtfgvtghiphhivghnthhsucdlqddutddtmd enucfjughrpefofgggkfgjfhffhffvufgtsegrtderreerredtnecuhfhrohhmpedflfho vghlucflrggtohgsshhonhdfuceojhhovghlsegtohhmphhilhgvrhdrohhrgheqnecugg ftrfgrthhtvghrnhephfdvhfeigedtgfdtvdetteejjeefgeeludfhgeduvdeuueduteel teegtefgvedvnecuffhomhgrihhnpehgihhthhhusgdrtghomhenucevlhhushhtvghruf hiiigvpedtnecurfgrrhgrmhepmhgrihhlfhhrohhmpehjohgvlhestghomhhpihhlvghr rdhorhhg X-ME-Proxy: Received: by mailuser.nyi.internal (Postfix, from userid 501) id AA119E00D4; Tue, 22 Dec 2020 12:45:16 -0500 (EST) X-Mailer: MessagingEngine.com Webmail Interface User-Agent: Cyrus-JMAP/3.3.1-61-gb52c239-fm-20201210.001-gb52c2396 Mime-Version: 1.0 Message-Id: <84d1730f-8784-4e30-bba5-01a99f3dfcc9@www.fastmail.com> In-Reply-To: <613704.1608654756@sss.pgh.pa.us> References: <613704.1608654756@sss.pgh.pa.us> Date: Tue, 22 Dec 2020 18:44:57 +0100 From: "Joel Jacobson" To: "Tom Lane" Cc: "Laurenz Albe" , "Philip Semanchuk" , pgsql-general Subject: Re: Avoid excessive inlining? Content-Type: multipart/alternative; boundary=af7f27c044294d94a3c2e374c7391cc4 X-Host-Lookup-Failed: Reverse DNS lookup failed for 64.147.123.24 (deferred) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk --af7f27c044294d94a3c2e374c7391cc4 Content-Type: text/plain Thanks Tom, this was exactly what I needed to hear. I guess I recently have become too fond of all the nice new "recent" advanced SQL features, such as LATERAL and MATERIALIZED CTEs, now in my possession since I now only code on hobby projects, after all the years stuck in an old PostgreSQL version in my previous job, to realise that such SQL features are not always a good fit for the job at all times. I rewrote all the slow pure SQL code in PL/pgSQL and got as 568% speed-up in the CBOR to JSON converter I'm working on. Thanks also for giving me inspiration on the wording for my own commit message: https://github.com/truthly/pg-cbor/commit/7ea7640f699cdf271ffa9cfb5d059f8141f541ed Author: Joel Jakobsson Date: Tue Dec 22 18:21:47 2020 +0100 Optimize by rewriting declarative pure SQL code into imperative PL/pgSQL PostgreSQL's SQL language isn't terribly well suited to execute a fundamentally stepwise, imperative algorithm like CBOR. Rather than hacking up cute tricks with LATERAL, we should just use a language that *is* well suited, a PL, like PL/pgSQL. -- Pure SQL (before): select * from pg_stat_xact_user_functions ; schemaname | funcname | calls | total_time | self_time ------------+------------+-------+------------+----------- cbor | next_item | 14 | 48.91024 | 38.964918 cbor | next_array | 1 | 7.297435 | 1.816102 cbor | next_map | 2 | 40.844352 | 7.8957 cbor | to_jsonb | 1 | 50.222183 | 1.311943 -- PL/pgSQL (after): select * from pg_stat_xact_user_functions ; schemaname | funcname | calls | total_time | self_time ------------+--------------+-------+------------+----------- cbor | next_item | 14 | 8.021371 | 3.358271 cbor | next_array | 1 | 0.565398 | 0.353071 cbor | next_map | 2 | 5.607702 | 1.324057 cbor | to_jsonb | 1 | 8.823691 | 0.80232 FUNCTIONS/major_type_0.sql | 23 +++++++++++++++++++++++ FUNCTIONS/major_type_1.sql | 23 +++++++++++++++++++++++ FUNCTIONS/major_type_2.sql | 23 +++++++++++++++++++++++ FUNCTIONS/major_type_3.sql | 23 +++++++++++++++++++++++ FUNCTIONS/major_type_4.sql | 23 +++++++++++++++++++++++ FUNCTIONS/major_type_5.sql | 23 +++++++++++++++++++++++ FUNCTIONS/major_type_6.sql | 40 ++++++++++++++++++++++++++++++++++++++++ FUNCTIONS/major_type_7.sql | 43 +++++++++++++++++++++++++++++++++++++++++++ FUNCTIONS/next_item.sql | 109 ++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------- Makefile | 8 ++++++++ expected/rfc7049_appendix_a.out | 52 +++++++++++++++++++++++++++++++++++++++------------- 11 files changed, 304 insertions(+), 86 deletions(-) Best regards, Joel On Tue, Dec 22, 2020, at 17:32, Tom Lane wrote: "Joel Jacobson" writes: > I think I was a bit unclear about my problem, and might have used the wrong terminology. > In my LATERAL query, there are calculations in a certain order. > For each step, "columns" are computed named e.g. "g", "c", "h", "i", etc. > However, when looking at the query plan, these steps are gone, and instead there is just one huge fully expanded expression, which doesn't look very efficient. Yeah, this isn't really about function inlining, it's about subquery flattening (which is similar in some ways, but not the same thing). Unfortunately, subquery flattening happens early enough in the planner that there's no chance of making any useful cost comparisons to decide whether to do it or not. So we just do it unconditionally. I'm not really sure that failing to do it would provide a better outcome in this situation anyway --- sure, you'd save a few scalar calculations, but the overhead of running additional plan nodes could outweigh that. The long and the short of it is that SQL isn't terribly well suited to execute a fundamentally stepwise, imperative algorithm like this one. Rather than hacking up cute tricks with LATERAL, you should just use a language that *is* well suited. That's why we provide PLs. FWIW, another trick for inserting optimization fences is WITH. So you could do something like WITH Q1(g,c) AS MATERIALIZED (SELECT year % 19, year / 100), Q2(h) AS MATERIALIZED (SELECT (c - c/4 - (8*c + 13)/25 + 19*g + 15) % 30 FROM Q1), ... SELECT make_date(year, easter_month, easter_day) FROM Q6; But I'd bet lunch that that won't be faster for this example, because there's a lot of overhead in CTEs. regards, tom lane Kind regards, Joel --af7f27c044294d94a3c2e374c7391cc4 Content-Type: text/html Content-Transfer-Encoding: quoted-printable
Thanks Tom,
=

this was exactly what I needed to hear.

I guess I recently have become too fond of all th= e nice new "recent" advanced SQL features,
such as LATERAL= and MATERIALIZED CTEs, now in my possession since I now only code on ho= bby
projects, after all the years stuck in an old PostgreS= QL version in my previous job,
to realise that such SQL fe= atures are not always a good fit for the job at all times.

I rewrote all the slow pure SQL code in PL/pgSQL and got= as 568% speed-up in the CBOR to JSON converter I'm working on. Thanks a= lso for giving me inspiration on the wording for my own commit message:<= br>

Date:=    Tue Dec 22 18:21:47 2020 +0100

    Optimize by rewriting declarative pure SQL code into= imperative PL/pgSQL

    Pos= tgreSQL's SQL language isn't terribly well suited to execute
    a fundamentally stepwise, imperative algorithm lik= e CBOR.

    Rather than hack= ing up cute tricks with LATERAL, we should just use
 =    a language that *is* well suited, a PL, like PL/pgSQL.
<= /div>

    -- Pure SQL (before):
    select * from pg_stat_xact_user_functions ;
     schemaname |  funcname  = | calls | total_time | self_time
    ------= ------+------------+-------+------------+-----------
 = ;    cbor       | next_item=   |    14 |   48.91024 | 38.964918
     cbor      = | next_array |     1 |   7.297435 | = 1.816102
     cbor   &= nbsp;   | next_map   |     2 |&n= bsp; 40.844352 |    7.8957
  &nbs= p;  cbor       | to_jsonb  = |     1 |  50.222183 |  1.311943

    -- PL/pgSQL (after):
    select * from pg_stat_xact_user_functions ;
     schemaname |   funcname =   | calls | total_time | self_time
   = ------------+--------------+-------+------------+-----------
<= div>     cbor       | = next_item    |    14 |   8.02137= 1 |  3.358271
     cbor &nbs= p;     | next_array   |   &= nbsp; 1 |   0.565398 |  0.353071
 &nbs= p;   cbor       | next_map =     |     2 |   5.607702 |&= nbsp; 1.324057
     cbor  &n= bsp;    | to_jsonb     |  &= nbsp;  1 |   8.823691 |   0.80232

FUNCTIONS/major_type_0.sql     = |  23 +++++++++++++++++++++++
FUNCTIONS/major_type_1= .sql      |  23 +++++++++++++++++++++++
FUNCTIONS/major_type_2.sql      |&n= bsp; 23 +++++++++++++++++++++++
FUNCTIONS/major_type_3.sql=       |  23 +++++++++++++++++++++++
FUNCTIONS/major_type_4.sql      | = 23 +++++++++++++++++++++++
FUNCTIONS/major_type_5.sql&nbs= p;     |  23 +++++++++++++++++++++++
<= div>FUNCTIONS/major_type_6.sql      |  40 = ++++++++++++++++++++++++++++++++++++++++
FUNCTIONS/major_t= ype_7.sql      |  43 +++++++++++++++++++++= ++++++++++++++++++++++
FUNCTIONS/next_item.sql  =        | 109 +++++++++++++++++++++++++++++= +++++++-----------------------------------------------------------------= --------
Makefile       = ;            = ;     |   8 ++++++++
expecte= d/rfc7049_appendix_a.out |  52 ++++++++++++++++++++++++++++++++++++= +++-------------
11 files changed, 304 insertions(+), 86 d= eletions(-)

Best regards,
Joel

On Tue, Dec 22, 2020, at 17:32= , Tom Lane wrote:
"Joel Jacobson" <joel@compiler.org>= ; writes:
> I think I was a bit unclear about my proble= m, and might have used the wrong terminology.
> In my L= ATERAL query, there are calculations in a certain order.
&= gt; For each step, "columns" are computed named e.g. "g", "c", "h", "i",= etc.
> However, when looking at the query plan, these = steps are gone, and instead there is just one huge fully expanded expres= sion, which doesn't look very efficient.

Ye= ah, this isn't really about function inlining, it's about subquery
flattening (which is similar in some ways, but not the same thi= ng).

Unfortunately, subquery flattening hap= pens early enough in the planner
that there's no chance of= making any useful cost comparisons to decide
whether to d= o it or not.  So we just do it unconditionally.  I'm
=
not really sure that failing to do it would provide a better outcom= e
in this situation anyway --- sure, you'd save a few scal= ar calculations,
but the overhead of running additional pl= an nodes could outweigh that.

The long and = the short of it is that SQL isn't terribly well suited to
= execute a fundamentally stepwise, imperative algorithm like this one.
Rather than hacking up cute tricks with LATERAL, you should = just use
a language that *is* well suited.  That's wh= y we provide PLs.

FWIW, another trick for i= nserting optimization fences is WITH.
So you could do some= thing like

WITH Q1(g,c) AS MATERIALIZED
=
  (SELECT year % 19, year / 100),
Q2(h) AS= MATERIALIZED
  (SELECT (c - c/4 - (8*c + 13)/25 + 19= *g + 15) % 30 FROM Q1),
...
SELECT make_date= (year, easter_month, easter_day) FROM Q6;

B= ut I'd bet lunch that that won't be faster for this example,
because there's a lot of overhead in CTEs.

regards, tom lane


Kind re= gards,

Joel

= --af7f27c044294d94a3c2e374c7391cc4--