Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 849110d

Browse files
Optimize sifting down in binaryheap.
Presently, each iteration of the loop in sift_down() will perform 3 comparisons if both children are larger than the parent node (2 for comparing each child to the parent node, and a third to compare the children to each other). By first comparing the children to each other and then comparing the larger child to the parent node, we can accomplish the same thing with just 2 comparisons (while also not affecting the number of comparisons in any other case). Author: ChangAo Chen Reviewed-by: Robert Haas Discussion: https://postgr.es/m/tencent_0142D8DA90940B9930BCC08348BBD6D0BB07%40qq.com
1 parent af21152 commit 849110d

File tree

1 file changed

+9
-20
lines changed

1 file changed

+9
-20
lines changed

src/common/binaryheap.c

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -323,34 +323,23 @@ sift_down(binaryheap *heap, int node_off)
323323
{
324324
int left_off = left_offset(node_off);
325325
int right_off = right_offset(node_off);
326-
int swap_off = 0;
326+
int swap_off = left_off;
327327

328-
/* Is the left child larger than the parent? */
329-
if (left_off < heap->bh_size &&
330-
heap->bh_compare(node_val,
331-
heap->bh_nodes[left_off],
332-
heap->bh_arg) < 0)
333-
swap_off = left_off;
334-
335-
/* Is the right child larger than the parent? */
328+
/* Is the right child larger than the left child? */
336329
if (right_off < heap->bh_size &&
337-
heap->bh_compare(node_val,
330+
heap->bh_compare(heap->bh_nodes[left_off],
338331
heap->bh_nodes[right_off],
339332
heap->bh_arg) < 0)
340-
{
341-
/* swap with the larger child */
342-
if (!swap_off ||
343-
heap->bh_compare(heap->bh_nodes[left_off],
344-
heap->bh_nodes[right_off],
345-
heap->bh_arg) < 0)
346-
swap_off = right_off;
347-
}
333+
swap_off = right_off;
348334

349335
/*
350-
* If we didn't find anything to swap, the heap condition is
336+
* If no children or parent is >= the larger child, heap condition is
351337
* satisfied, and we're done.
352338
*/
353-
if (!swap_off)
339+
if (left_off >= heap->bh_size ||
340+
heap->bh_compare(node_val,
341+
heap->bh_nodes[swap_off],
342+
heap->bh_arg) >= 0)
354343
break;
355344

356345
/*

0 commit comments

Comments
 (0)