Re: Reduce one comparison in binaryheap's sift down

From: Robert Haas <robertmhaas(at)gmail(dot)com>
To: cca5507 <cca5507(at)qq(dot)com>
Cc: pgsql-hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Reduce one comparison in binaryheap's sift down
Date: 2024-10-28 16:40:20
Message-ID: CA+TgmoZ8_aNP627=QPJSfvp0mtdxbuyu2_c6KQSdDJKcUkVA2w@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Mon, Oct 28, 2024 at 11:22 AM cca5507 <cca5507(at)qq(dot)com> wrote:
> I think we can reduce one comparison in binaryheap's sift down, right?
>
> Here is a patch to fix it.

Hmm, so at present we compare the parent to the left child and to the
right child. If it's smaller than neither, everything is OK. If it's
smaller than one, we swap it with that one. If it's smaller than both,
we compare the left and right child with each other and swap the
parent with the larger of the two. Hence, if a node has 2 children, we
always do 2 comparisons, and we sometimes do 3 comparisons.

With the patch, we first compare the two children to each other, and
then compare the larger one to the parent. If the parent is smaller
than the larger child, we swap them. Hene, if a node has 2 children,
we always do 2 comparisons.

Unless I'm missing something, that does seem significantly better.

--
Robert Haas
EDB: http://www.enterprisedb.com

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Aleksander Alekseev 2024-10-28 16:48:05 Re: general purpose array_sort
Previous Message Peter Geoghegan 2024-10-28 16:38:24 Re: Adding skip scan (including MDAM style range skip scan) to nbtree