Redis須要你來作的算法優化

         閱讀一個優秀的Server內核實現,早期的代碼比後期的代碼要好得多。由於在早期的代碼裏,你能夠學習到一個***級別的程序猿到底在思考什麼。同時,你能看到他哪裏寫得差勁,以及後來是怎麼優化的。html

         若是你一心追求最新的技術,可是,不關心它是怎麼成長起來的,方向都走錯了。走錯了方向,跑得越快,離目標越遠。ide

/* Search the first timer to fire.
 * This operation is useful to know how many time the select can be
 * put in sleep without to delay any event.
 * If there are no timers NULL is returned.
 *
 * Note that's O(N) since time events are unsorted.
 * Possible optimizations (not needed by Redis so far, but...):
 * 1) Insert the event in order, so that the nearest is just the head.
 *    Much better but still insertion or deletion of timers is O(N).
 * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
 */
static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop)
{
    aeTimeEvent *te = eventLoop->timeEventHead;
    aeTimeEvent *nearest = NULL;

    while(te) {
        if (!nearest || te->when_sec < nearest->when_sec ||
                (te->when_sec == nearest->when_sec &&
                 te->when_ms < nearest->when_ms))
            nearest = te;
        te = te->next;
    }
    return nearest;
}


Redis在查找最近的時間事件的時候,採用了暴力遍歷,時間複雜度是O(N)。優化的方法做者想到了2種,可是他並無實現,或許他以爲這個不是最緊迫的事情。oop

須要嘗試一下嗎?學習

相關文章
相關標籤/搜索