In file stdlib/qsort.c, why is swapping elements code so complex?
Amit
amitchoudhary0523@gmail.com
Thu Jan 29 07:11:13 GMT 2026
> >
> > The complex logic you're complaining about *is* an improvement. Lots of
> > effort has gone in to making qsort faster and more robust.
>
>
> There is always a tradeoff between speed and code complexity. I prefer
> code complexity when the performance gains are significant (more than
> 50% performance gain). Here, in qsort(), the complex code will not be
> much more efficient than swapping bytes using a temporary variable.
>
I did an experiment. Swapping integers is only around 13% faster than
swapping 4 bytes/characters one by one.
""""So, in my opinion, 13% performance improvement doesn't warrant
such complex swapping elements code in qsort() function.""""
The code that I wrote for the experiment is below:
---------------
swap_int.c
---------------
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
void swap_int(int *iptr, int *jptr)
{
int temp = 0;
temp = *iptr;
*iptr = *jptr;
*jptr = temp;
} // end of function swap_int()
int main(void)
{
int i = 0;
int j = 0;
int k = 0;
int max = INT_MAX/4;
srand((unsigned int)(time(NULL)));
for (k = 0; k < max; k++) {
i = rand();
j = rand();
swap_int(&i, &j);
} // end of for loop
} // end of function main()
-----------------
swap_char.c
-----------------
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
void swap_char(char *iptr, char *jptr)
{
int a = 0;
int num_bytes = sizeof(int);
unsigned char temp = 0;
for (a = 0; a < num_bytes; a++) {
temp = iptr[a];
iptr[a] = jptr[a];
jptr[a] = temp;
}
} // end of function swap_char()
int main(void)
{
int i = 0;
int j = 0;
int k = 0;
int max = INT_MAX/4;
srand((unsigned int)(time(NULL)));
for (k = 0; k < max; k++) {
i = rand();
j = rand();
swap_char((char *)(&i), (char *)(&j));
} // end of for loop
} // end of function main()
""""And gcc didn't optimize the functions away because I didn't use
any optimization flag. You can check yourself by generating the
assembly code of the programs that I gave above and you will see that
the functions are present in the assembly code.""""
I compiled the programs using the following command: gcc swap_int.c -o
swap_int.out (and similarly for swap_char.c).
I generated the assembly code of the programs using the following
command: gcc -S swap_int.c (and similarly for swap_char.c).
Amit
More information about the Libc-alpha
mailing list