Optimize expandMacro() a bit, based on patch by Alexey Tourbin

- Avoid the expensive calloc() when creating a macro expansion buffer,
  malloc() suffices just as well as long as we initialize the first
  byte in the buffer. This is easily visible on wall-clock times.
- Avoid recalculating source string length: when caller doesn't
  pass slen, we always calculate the string length for creating
  a terminated copy, no need to redo it...
- Add a warning comment about the seemingly obvious optimization
  breaking macro undefining itself, this is starting to look like
  a recurring theme :)
This commit is contained in:
Panu Matilainen 2013-04-16 10:45:56 +03:00
parent 84fb114457
commit c012a76985
1 changed files with 9 additions and 3 deletions

View File

@ -986,7 +986,12 @@ expandMacro(MacroBuf mb, const char *src, size_t slen)
int chkexist; int chkexist;
char *source = NULL; char *source = NULL;
/* Handle non-terminated substrings by creating a terminated copy */ /*
* Always make a (terminated) copy of the source string.
* Beware: avoiding the copy when src is known \0-terminated seems like
* an obvious opportunity for optimization, but doing that breaks
* a special case of macro undefining itself.
*/
if (!slen) if (!slen)
slen = strlen(src); slen = strlen(src);
source = xmalloc(slen + 1); source = xmalloc(slen + 1);
@ -995,8 +1000,9 @@ expandMacro(MacroBuf mb, const char *src, size_t slen)
s = source; s = source;
if (mb->buf == NULL) { if (mb->buf == NULL) {
size_t blen = MACROBUFSIZ + strlen(s); size_t blen = MACROBUFSIZ + slen;
mb->buf = xcalloc(blen + 1, sizeof(*mb->buf)); mb->buf = xmalloc(blen + 1);
mb->buf[0] = '\0';
mb->tpos = 0; mb->tpos = 0;
mb->nb = blen; mb->nb = blen;
} }