Performance gain by avoiding arguments check is very small (less then 1%).

Amit amitchoudhary0523@gmail.com
Mon Sep 29 16:35:38 GMT 2025


To be sure I did one more experiment. This time I used qsort() and I
validated 4 arguments.

=========================================
I found out that the performance gain is only 2.61%. In my last experiment
where I was checking only 1 argument the performance improvement was
0.775%. So, per argument you get a gain of between 0.65% to 0.775%.

I don't remember which glibc/POSIX function has the maximum number of
arguments but assuming that the max number is 5, then you will get only
3.25% - 3.875% performance gain.

Does this small gain justify not validating the arguments? In my opinion,
it doesn't. But definitely, you guys can think otherwise.
=========================================

Below is the code and the result:

-----------------------
measure_qsort.c
------------------------

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#define MAX_NMEMB_ALLOWED 100*1024*1024 // 100 MB

#define MAX_MEMBER_SIZE_ALLOWED 1024

typedef int (*COMP_FUNC)(const void *elem1, const void *elem2);

int comp_func(const void *elem1, const void *elem2)
{

    if ((elem1 == NULL) && (elem2 == NULL)) {
        return 0;
    } else if (elem1 == NULL) {
        return -1;
    } else if (elem2 == NULL) {
        return 1;
    }

    return ((*((int *)(elem1))) - (*((int *)(elem2))));
}

void do_qsort(void *arr, size_t nmemb, size_t size, COMP_FUNC comp_func)
{

#if 0
    if (!arr) {
        return;
    }

    if ((nmemb <= 0) || (nmemb > MAX_MEMBER_SIZE_ALLOWED)) {
        return;
    }

    if ((size <= 0) || (size > MAX_MEMBER_SIZE_ALLOWED)) {
        return;
    }

    if (!comp_func) {
        return;
    }
#endif

    qsort(arr, nmemb, size, comp_func);

}

int main(void)
{

    int arr[4] = {20, 1, 50, 3};
    int i = 0;

    do_qsort(arr, 4, 4, comp_func);

    exit(EXIT_SUCCESS);

}

-------------------------------
run_measure_qsort.sh
-------------------------------

#!/bin/bash

count=0

while true
do
    if [ "$count" -eq 100000 ]; then
        exit
    fi
    ./a.out
    count=$((count+1))
done

======
Result
======

------------------------------------
With arguments validation
------------------------------------

real 0m50.952s
user 0m36.610s
sys 0m17.766s

Total: user + sys = 54.376 seconds

----------------------------------------
Without arguments validation
----------------------------------------

real 0m49.701s
user 0m35.723s
sys 0m17.235s

Total: user + sys = 52.958 seconds

Performance improvement without arguments validation: 2.61%

--------------------------------------------------------------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://sourceware.org/pipermail/libc-alpha/attachments/20250929/849d78a3/attachment.htm>


More information about the Libc-alpha mailing list