C Redis源代码中的if-else块(简单动态字符串),我无法';我不明白

C Redis源代码中的if-else块(简单动态字符串),我无法';我不明白,c,redis,C,Redis,首先,我真的很抱歉这个标题,但我不知道我该怎么说 我试着去理解,在第138-141行之间有一个if-else块,我无法理解。我甚至不知道它为什么在那里,我也不知道它做什么 有关职能是: /* Enlarge the free space at the end of the sds string so that the caller * is sure that after calling this function can overwrite up to addlen * bytes after

首先,我真的很抱歉这个标题,但我不知道我该怎么说

我试着去理解,在第138-141行之间有一个if-else块,我无法理解。我甚至不知道它为什么在那里,我也不知道它做什么

有关职能是:

/* Enlarge the free space at the end of the sds string so that the caller
* is sure that after calling this function can overwrite up to addlen
* bytes after the end of the string, plus one more byte for nul term.
*
* Note: this does not change the *length* of the sds string as returned
* by sdslen(), but only the free buffer space we have. */
sds sdsMakeRoomFor(sds s, size_t addlen) {
    struct sdshdr *sh, *newsh;
    size_t free = sdsavail(s);
    size_t len, newlen;

    if (free >= addlen) return s;
    len = sdslen(s);
    sh = (void*) (s-(sizeof(struct sdshdr)));
    newlen = (len+addlen);
    if (newlen < SDS_MAX_PREALLOC) /* unwind: line 138 */
        newlen *= 2;
    else
        newlen += SDS_MAX_PREALLOC;
    newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1);
    if (newsh == NULL) return NULL;

    newsh->free = newlen - len;
    return newsh->buf;
}
/*放大sds字符串末尾的可用空间,以便调用者
*确定调用此函数后最多可以覆盖addlen
*字符串结尾后的字节,再加上一个字节表示nul term。
*
*注意:这不会更改返回的sds字符串的*长度*
*通过sdslen(),但只有可用的缓冲区空间*/
sds sdsMakeRoomFor(sds s,尺寸和地址){
结构sdshdr*sh,*newsh;
自由尺寸=sdsavail(s);
大小_t len,newlen;
如果(free>=addlen)返回s;
len=sdslen(s);
sh=(void*)(s-(sizeof(struct sdshdr));
newlen=(len+addlen);
如果(newlenfree=newlen-len;
返回newsh->buf;
}
很抱歉提出这样的问题,但我们将非常感谢您的帮助。

我想您了解它的作用,但不了解原因

如果计算的增量被认为“太小”,则what is is将使分配用于保存字符串的缓冲区大小的增量加倍

为什么要提高性能:如果字符串继续增长(动态字符串可以做到这一点),Redis就不需要像以前那样尽快重新分配新的缓冲区。这很好,因为
realloc()
成本很高

基本上,它是通过消耗内存来购买性能,这是一种非常常见的权衡