From 337cb90eb37c5982e2d7f2dc6ab70fbb500c6010 Mon Sep 17 00:00:00 2001
From: Stepan Neretin <sndcppg@gmail.com>
Date: Sun, 8 Sep 2024 15:44:00 +0700
Subject: [PATCH v2 04/10] Optimized Integer List Sorting by Using Template
 Sorting Algorithm

Optimized the sorting of lists containing integers by utilizing a custom sort template.
This enhancement introduces a specialized sorting function sort_list_int defined through macros and included from sort_template.h.
The new function improves performance by directly comparing integers and sorting the list in-place.

Changes:
- Defined ST_SORT, ST_ELEMENT_TYPE, ST_COMPARE, ST_SCOPE, and ST_DEFINE macros for sort_list_int.
- Included sort_template.h to leverage the template-based sorting mechanism.
- Implemented list_int_sort function to sort lists with int type.

This optimization is expected to enhance the efficiency of sorting operations for integer lists, leading to overall performance improvements in systems that manage large lists of integers.
---
 src/backend/nodes/list.c    | 14 ++++++++++++++
 src/include/nodes/pg_list.h |  1 +
 2 files changed, 15 insertions(+)

diff --git a/src/backend/nodes/list.c b/src/backend/nodes/list.c
index b2165c6284..197ce1b8f4 100644
--- a/src/backend/nodes/list.c
+++ b/src/backend/nodes/list.c
@@ -1720,4 +1720,18 @@ list_oid_cmp(const ListCell *p1, const ListCell *p2)
  */
 void list_oid_sort(List *data){
    sort_list_oids(list_head(data), list_length(data));
+}
+
+#define ST_SORT sort_list_ints
+#define ST_ELEMENT_TYPE ListCell
+#define ST_COMPARE(a, b) list_int_cmp(a, b)
+#define ST_SCOPE static
+#define ST_DEFINE
+#include <lib/sort_template.h>
+
+/*
+ * Sort list with int type optimization.
+ */
+void list_int_sort(List *data){
+   sort_list_ints(list_head(data), list_length(data));
 }
\ No newline at end of file
diff --git a/src/include/nodes/pg_list.h b/src/include/nodes/pg_list.h
index 88aa1ebea9..7757b1cdf0 100644
--- a/src/include/nodes/pg_list.h
+++ b/src/include/nodes/pg_list.h
@@ -680,6 +680,7 @@ extern pg_nodiscard List *list_copy_deep(const List *oldlist);
 typedef int (*list_sort_comparator) (const ListCell *a, const ListCell *b);
 extern void list_sort(List *list, list_sort_comparator cmp);
 extern void list_oid_sort(List *list);
+extern void list_int_sort(List *list);
 
 extern int	list_int_cmp(const ListCell *p1, const ListCell *p2);
 extern int	list_oid_cmp(const ListCell *p1, const ListCell *p2);
-- 
2.43.0

