If one can choose to fwrite() 100 1 bytes, or 1 100 bytes, which approach should be prefered?

I am interested if there is a theoretical speed difference between

fwrite(str , 1 , 100 , fp );

and

fwrite(str , 100 , 1 , fp );

based on how the function is written in glibc, and how many write calls it makes and how it is buffered (disregarding hardware differences on gcc).

>Solution :

There’s no difference for musl or glibc, or the FreeBSD libc since they all call an underlying function with size*nmemb:

musl

size_t fwrite(const void *restrict src, size_t size, size_t nmemb, FILE *restrict f)
{
    size_t k, l = size*nmemb;
    // ...
    k = __fwritex(src, l, f);

glibc

size_t
_IO_fwrite (const void *buf, size_t size, size_t count, FILE *fp)
{
  size_t request = size * count;
  // ...
  written = _IO_sputn (fp, (const char *) buf, request);

freebsd

    n = count * size;
    // ...
    uio.uio_resid = iov.iov_len = n;
    // ...
    if (__sfvwrite(fp, &uio) != 0)

Leave a Reply