LRU算法的PHP實現


<?php
/**
 * LRU是最近最少使用頁面置換算法(Least Recently Used),也就是首先淘汰最長時間未被使用的頁面
 */
class LRU_Cache
{

    private $array_lru = array();
    private $max_size = 0;

    function __construct($size)
    {
        // 緩存最大存儲
        $this->max_size = $size;
    }

    public function set_value($key, $value)
    {
        // 如果存在,則向隊尾移動,先刪除,后追加
        if (array_key_exists($key, $this->array_lru)) {
            unset($this->array_lru[$key]);
        }
        // 長度檢查,超長則刪除首元素
        if (count($this->array_lru) > $this->max_size) {
            array_shift($this->array_lru);
        }
        // 隊尾追加元素
        $this->array_lru[$key] = $value;
    }

    public function get_value($key)
    {
        $ret_value = false;

        if (array_key_exists($key, $this->array_lru)) {
            $ret_value = $this->array_lru[$key];
            // 移動到隊尾
            unset($this->array_lru[$key]);
            $this->array_lru[$key] = $ret_value;
        }
        
        return $ret_value;
    }

    public function vardump_cache()
    {
        var_dump($this->array_lru);
    }
}

$cache = new LRU_Cache(5);
$cache->set_value("01", "01");
$cache->set_value("02", "02");
$cache->set_value("03", "03");
$cache->set_value("04", "04");
$cache->set_value("05", "05");
$cache->vardump_cache();
$cache->set_value("06", "06");
$cache->vardump_cache();
$cache->set_value("03", "03");
$cache->vardump_cache();
$cache->set_value("07", "07");
$cache->vardump_cache();
$cache->set_value("01", "01");
$cache->vardump_cache();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM