huangzworks/redis-3.0-annotated

sdscatvprintf 时间复杂度问题

leexingliang opened this issue · 0 comments

源码中对 sdscatvprintf 这个函数的时间复杂度分析

/* Try with buffers two times bigger every time we fail to
     * fit the string in the current buffer size. */
    while(1) {
        buf[buflen-2] = '\0';
        va_copy(cpy,ap);
        // T = O(N)
        vsnprintf(buf, buflen, fmt, cpy);
        if (buf[buflen-2] != '\0') {
            if (buf != staticbuf) zfree(buf);
            buflen *= 2;
            buf = zmalloc(buflen);
            if (buf == NULL) return NULL;
            continue;
        }
        break;
    }

buf 每次是两倍的长度增长, 时间复杂度应该是 n*logn
n 代表 fmt 字符串的长度