]> git.ipfire.org Git - thirdparty/glibc.git/commit
stdlib: Remove use of mergesort on qsort (BZ 21719)
authorAdhemerval Zanella <adhemerval.zanella@linaro.org>
Tue, 3 Oct 2023 12:22:50 +0000 (09:22 -0300)
committerAdhemerval Zanella <adhemerval.zanella@linaro.org>
Tue, 31 Oct 2023 17:18:05 +0000 (14:18 -0300)
commit03bf8357e8291857a435afcc3048e0b697b6cc04
treed4f97004d712dd066458d15f9be599fc964d5d7b
parent274a46c9b25ab733a1fb9fb1497f1beecae30193
stdlib: Remove use of mergesort on qsort (BZ 21719)

This patch removes the mergesort optimization on qsort implementation
and uses the introsort instead.  The mergesort implementation has some
issues:

  - It is as-safe only for certain types sizes (if total size is less
    than 1 KB with large element sizes also forcing memory allocation)
    which contradicts the function documentation.  Although not required
    by the C standard, it is preferable and doable to have an O(1) space
    implementation.

  - The malloc for certain element size and element number adds
    arbitrary latency (might even be worse if malloc is interposed).

  - To avoid trigger swap from memory allocation the implementation
    relies on system information that might be virtualized (for instance
    VMs with overcommit memory) which might lead to potentially use of
    swap even if system advertise more memory than actually has.  The
    check also have the downside of issuing syscalls where none is
    expected (although only once per execution).

  - The mergesort is suboptimal on an already sorted array (BZ#21719).

The introsort implementation is already optimized to use constant extra
space (due to the limit of total number of elements from maximum VM
size) and thus can be used to avoid the malloc usage issues.

Resulting performance is slower due the usage of qsort, specially in the
worst-case scenario (partialy or sorted arrays) and due the fact
mergesort uses a slight improved swap operations.

This change also renders the BZ#21719 fix unrequired (since it is meant
to fix the sorted input performance degradation for mergesort).  The
manual is also updated to indicate the function is now async-cancel
safe.

Checked on x86_64-linux-gnu.
Reviewed-by: Noah Goldstein <goldstein.w.n@gmail.com>
include/stdlib.h
manual/argp.texi
manual/locale.texi
manual/search.texi
stdlib/Makefile
stdlib/msort.c [deleted file]
stdlib/qsort.c