From beb5b92d04075b0539f2a6965f58d6a63ae2898e Mon Sep 17 00:00:00 2001
From: Stepan Neretin <sncfmgg@gmail.com>
Date: Sat, 8 Jun 2024 00:14:18 +0700
Subject: [PATCH v42 4/6] Optimized Int List Sorting by using template sorting
 algorithm

This commit optimizes the sorting of integer lists by implementing a custom sort template algorithm. It introduces a specialized sorting function, `list_int_sort`, defined through macros and included from `sort_template.h`. The enhancement aims to improve performance by enabling direct comparison of integers and sorting the list in-place.

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

This optimization is expected to provide better sorting efficiency for lists containing Ints, contributing to overall system performance improvements.
---
 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 e10ce545ad..197ce1b8f4 100644
--- a/src/backend/nodes/list.c
+++ b/src/backend/nodes/list.c
@@ -1721,3 +1721,17 @@ 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.34.1

