Re: Sort functions with specialized comparators

x4mmm@yandex-team.ru

From: "Andrey M. Borodin" <x4mmm@yandex-team.ru>
To: John Naylor <johncnaylorls@gmail.com>
Cc: David Rowley <dgrowleyml@gmail.com>, Антуан Виолин <violin.antuan@gmail.com>, PostgreSQL Hackers <pgsql-hackers@postgresql.org>
Date: 2025-01-07T05:59:22Z
Lists: pgsql-hackers

> On 7 Jan 2025, at 09:43, John Naylor <johncnaylorls@gmail.com> wrote:
> 
>> With the same setup as in the first message of this thread we can do:
>> 
>> postgres=# SELECT _int_contains(arr,ARRAY[1]) FROM arrays_to_sort;
>> 
>> before patch patch
>> Time: 567.928 ms
>> after patch
>> Time: 890.297 ms
>> timing of this function is dominated by PREPAREARR(a);
>> 
>> What bothers me is that PREPAREARR(a); is returning new array in case of empty input. That's why I considered little refactoring of resize_intArrayType(): reorder cases so that if (num == ARRNELEMS(a)) was first.
> 
> Hmm, I'm confused. First, none of the arrays are empty that I can see
> -- am I missing something?

Ugh...sorry, I posted very confusing results. For starters, I swapped "patched" and "unpatched" results. So results show clear improvement in default case.

I'm worried about another case that we cannot measure: PREPAREARR(a) on empty array will return new array.

And one more case.
BTW for pre-sorted desc arrays desc sorting is slower:
postgres=# CREATE TABLE arrays_sorted_desc AS                                                            
	SELECT a arr                                                                                           
		FROM                                                                                                       
		(SELECT ARRAY(SELECT -i from generate_series(1, 1000000)i) a),                                         
		 generate_series(1, 10);
SELECT 10
Time: 707.016 ms
postgres=# SELECT (sort_desc(arr))[0] FROM arrays_sorted_desc;
Time: 41.874 ms

but with a patch
postgres=# SELECT (sort_desc(arr))[0] FROM arrays_sorted_desc;
Time: 166.837 ms


Best regards, Andrey Borodin.


Commits

  1. Specialize intarray sorting

  2. Replace insertion sort in contrib/intarray with qsort().