Eric Blake wrote:
> one _very_ common use of snprintf is to call it with size 0 to see
> how much to allocate, then allocate and call again.
Why do people do this? It appears to be slower than just calling
asprintf, because it has to parse the format string and produce
the expansion twice.
====================== foo.c ==========================
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int REPEAT = atoi (argv[1]);
int ALGO = atoi (argv[2]);
const char *fmt = "%d";
int arg1 = 12345;
if (ALGO == 0)
{
int repeat;
for (repeat = REPEAT; repeat > 0; repeat--)
{
int len = snprintf (NULL, 0, fmt, arg1);
char *mem = malloc (len + 1);
snprintf (mem, len + 1, fmt, arg1);
free (mem);
}
}
else
{
int repeat;
for (repeat = REPEAT; repeat > 0; repeat--)
{
char *mem;
if (asprintf (&mem, fmt, arg1) < 0)
abort ();
free (mem);
}
}
return 0;
}
==============================================================================
I get timings like
$ time ./a.out 10000000 0
real 0m4.253s
user 0m4.248s
sys 0m0.004s
$ time ./a.out 10000000 1
real 0m4.035s
user 0m4.028s
sys 0m0.004s
That is, snprintf + malloc + snprintf is slower than asprintf.
Bruno